package com.sailfish.springbootdemo.service.db7.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db4.EmailReminderDao;
import com.sailfish.springbootdemo.dao.db4.TimerConfigDao;
import com.sailfish.springbootdemo.dao.db4.User2Dao;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.dao.db5.PdmNewPartApplicationDao;
import com.sailfish.springbootdemo.dao.db5.PdmPartPackageInfoDao;
import com.sailfish.springbootdemo.dao.db7.*;
import com.sailfish.springbootdemo.dao.db8.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.EmailReminder;
import com.sailfish.springbootdemo.pojo.db4.TimerConfig;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.pojo.db4.User2;
import com.sailfish.springbootdemo.pojo.db5.PdmNewPartApplication;
import com.sailfish.springbootdemo.pojo.db5.PdmPartPackageInfo;
import com.sailfish.springbootdemo.pojo.db7.*;
import com.sailfish.springbootdemo.pojo.db8.*;
import com.sailfish.springbootdemo.service.db2.S3UploadFileService;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db7.CommonService;
import com.sailfish.springbootdemo.service.db7.QueryKnowledgeBaseDataService;
import com.sailfish.springbootdemo.service.db7.TaskCenterService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ExcelUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import com.sailfish.springbootdemo.utils.SfsUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Slf4j
@Service
@Component
public class TaskCenterServiceImpl implements TaskCenterService {
    @Value("${personal.config.amazon-s3.url}")
    private String url;

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.env}")
    private String env;

    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;

    @Autowired
    private TbTemplateDao tbTemplateDao;
    @Autowired
    private TbTemplateVersionDao tbTemplateVersionDao;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TbFlowDetailDao tbFlowDetailDao;
    @Autowired
    private TbFlowProcessDetailDao tbFlowProcessDetailDao;
    @Autowired
    private TbFlowProcessMainDao tbFlowProcessMainDao;
    @Autowired
    private TbFlowProcessRecordsDao tbFlowProcessRecordsDao;
    @Autowired
    private TbTaskVersionDao tbTaskVersionDao;

    @Autowired
    private TbTaskTemplateDataDao tbTaskTemplateDataDao;

    @Autowired
    private TbFlowCompVplDao tbFlowCompVplDao;

    @Autowired
    private TbFlowCompPkgDao tbFlowCompPkgDao;

    @Autowired
    private TbFlowCompManufacturerDao tbFlowCompManufacturerDao;

    @Autowired
    private TbFlowCompVplAttrDao tbFlowCompVplAttrDao;

    @Autowired
    private TbFlowCompVplPinAttrDao tbFlowCompVplPinAttrDao;

    @Autowired
    private TbFlowCompVplPdmDao tbFlowCompVplPdmDao;

    @Autowired
    private MpackageDao mpackageDao;

    @Autowired
    private PdmNewPartApplicationDao pdmNewPartApplicationDao;


    @Autowired
    private TbKnowledgeBaseFileDao tbKnowledgeBaseFileDao;

    @Autowired
    private TbKnowledgeBaseDataDao tbKnowledgeBaseDataDao;

    @Autowired
    private TbFlowCompVplPinNumberDao tbFlowCompVplPinNumberDao;

    @Autowired
    private TbKnowledgeBaseConfigDao tbKnowledgeBaseConfigDao;

    @Autowired
    private User2Dao user2Dao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private vVplPartDataDao _vVplPartDataDao;


    @Autowired
    private vVplPackageDao _vVplPackageDao;

    @Autowired
    private PdmPartPackageInfoDao pdmPartPackageInfoDao;

    @Autowired
    private ThirdApiService thirdApiService;
    @Value("${personal.config.knowledgeBaseFlowUrl.baseUrl}")
    private String knowledgeBaseFlowUrl;
    @Value("${personal.config.knowledgeBaseFlowUrl.vpl}")
    private String vplUrl;
    @Value("${personal.config.knowledgeBaseFlowUrl.device}")
    private String deviceUrl;
    @Value("${personal.config.knowledgeBaseFlowUrl.design}")
    private String designUrl;

    @Autowired
    S3UploadFileService s3UploadFileService;

    @Autowired
    private IntfFromVplWebPackageDao intfFromVplWebPackageDao;

    @Autowired
    private IntfFromVplWebPartdataDao intfFromVplWebPartdataDao;

    @Autowired
    private IntfFromVplWebPinattrDao intfFromVplWebPinattrDao;
    @Autowired
    private IntfFromVplWebPinnumberDao intfFromVplWebPinnumberDao;

    @Autowired
    private QueryKnowledgeBaseDataService queryKnowledgeBaseDataService;

    @Autowired
    private TbKnowledgeBasePushLogicDao tbKnowledgeBasePushLogicDao;

    @Autowired
    SfsUtils sfsUtils;

    @Autowired
    private TimerConfigDao timerConfigDao;

    @Autowired
    private EmailReminderDao emailReminderDao;

    private static final Map<Integer, String> ruleMap = new HashMap<>();

    static {
        ruleMap.put(1, "包含");
        ruleMap.put(2, "不包含");
        ruleMap.put(3, "超过");
        ruleMap.put(4, "不超过");
        ruleMap.put(5, "等于");
        ruleMap.put(6, "不等于");
        ruleMap.put(7, "小于");
        ruleMap.put(8, "不小于");
    }

    @Override
    public Result getTaskFlow(String data) {

        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);
                //流程类型
                String _flow_type = jsonObject.getString("flow_type");
                String _flow_no = jsonObject.getString("flow_no");
                String _type = jsonObject.getString("type");
                Integer _now_level = jsonObject.getInteger("now_level");

                if (_type == null || (!_type.equals("key") && !_type.equals("value"))) {
                    return ResultUtil.error(500, "type 只支持key&value", "", null);
                }

                if (_now_level == null) {
                    _now_level = 9999;
                }

                //判断流程类型是不是标准值vpl,device,design
                if (_flow_type != null && (_flow_type.equals("vpl") || _flow_type.equals("device") || _flow_type.equals("design"))) {
                    //获取到了流程节点信息
                    String tempTemplate_type = "";
                    if (_flow_type.equals("device")) {
                        tempTemplate_type = "deviceType";
                    }

                    if (_flow_type.equals("design")) {
                        tempTemplate_type = "designType";
                    }

                    //VPL流程里面也都是器件信息的模板
                    if (_flow_type.equals("vpl")) {
                        tempTemplate_type = "deviceType";
                    }

                    if (_flow_no != null && !_flow_no.isEmpty()) {
                        if (_flow_type.equals("design") || _flow_type.equals("device")) {

                            List<TbFlowProcessMain> listFlowProcessMain = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);
                            if (listFlowProcessMain == null || listFlowProcessMain.size() <= 0) {
                                return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                            }

                            TbFlowProcessMain tbFlowProcessMain = listFlowProcessMain.get(0);
                            Integer now_level = tbFlowProcessMain.getNow_level();

                            now_level = _now_level;
                            //if(tbFlowProcessMain.getStatus()==3)
                            //{
                            //    now_level=9999;
                            //}

                            //还要获取一下当前的流程节点信息
                            List<TbFlowProcessDetail> listFlowProcessDetail = tbFlowProcessDetailDao.getFlowDetailsByFlowNo(_flow_no);

                            if (listFlowProcessDetail == null || listFlowProcessDetail.size() <= 0) {
                                return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                            }
                            //获取数据库现在所有的条目信息
                            List<TbTaskTemplateData> listTaskTemplateData = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(_flow_no);
                            if (listTaskTemplateData == null || listTaskTemplateData.size() == 0) {
                                return ResultUtil.error(500, "没有取到数据", "", null);
                            }

                            List<Map<String, Object>> combinedList = new ArrayList<>();

                            for (TbFlowProcessDetail flowInfo : listFlowProcessDetail) {
                                Map<String, Object> combinedMap = new HashMap<>();
                                combinedMap.put("id", flowInfo.getId());
                                combinedMap.put("flow_type", flowInfo.getFlow_type());
                                combinedMap.put("flow_name", flowInfo.getFlow_name());
                                combinedMap.put("flow_level", flowInfo.getFlow_level());
                                combinedMap.put("knowledge_base_key", tbFlowProcessMain.getKnowledge_base_key());
                                combinedMap.put("flow_approver", flowInfo.getFlow_approver());
                                combinedMap.put("sort", flowInfo.getSort());
                                //combinedMap.put("create_time", flowInfo.getCreate_time());
                                combinedMap.put("create_user", flowInfo.getCreate_user());

                                try {
                                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    combinedMap.put("create_time", sfd.format(flowInfo.getCreate_time()));
                                } catch (Exception e) {
                                    combinedMap.put("create_time", flowInfo.getCreate_time());
                                }

                                try {
                                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    combinedMap.put("update_time", sfd.format(flowInfo.getUpdate_time()));
                                } catch (Exception e) {
                                    combinedMap.put("update_time", flowInfo.getUpdate_time());
                                }
                                combinedMap.put("update_user", flowInfo.getUpdate_user());
                                combinedMap.put("remark", flowInfo.getRemark());
                                combinedMap.put("status", flowInfo.getStatus());
                                String flowApprovers = flowInfo.getFlow_approver();
                                if (flowApprovers != null && !flowApprovers.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));

                                    combinedMap.put("flow_approver_list", flowApproverList);
                                    combinedMap.put("flow_approver_info", user2Dao.getUserInfoByIds(flowApproverList));
                                }

                                combinedMap.put("flow_approver_authorize", flowInfo.getFlow_approver_authorize());
                                combinedMap.put("comments", flowInfo.getComments());
                                combinedMap.put("designer", flowInfo.getDesigner());

                                String designer = flowInfo.getDesigner();
                                if (designer != null && !designer.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> designerList = Arrays.asList(designer.split(","));
                                    combinedMap.put("designer_info", user2Dao.getUserInfoByIds(designerList));
                                }

                                String vpl_create_user = flowInfo.getVpl_create_user();
                                if (vpl_create_user != null && !vpl_create_user.isEmpty()) {

                                    List<String> vpl_create_userList = Arrays.asList(vpl_create_user.split(","));

                                    //combinedMap.put("vpl_create_user_list", vpl_create_userList);
                                    combinedMap.put("vpl_create_user_info", user2Dao.getUserInfoByIds(vpl_create_userList));
                                } else {
                                    combinedMap.put("vpl_create_user_info", null);
                                }
                                combinedMap.put("vpl_create_user", vpl_create_user);

                                // 判断是否添加 basicInfo
                                if (flowInfo.getFlow_level() == 1) {

                                    Map<String, String> keyMap = new HashMap<>();

                                    // 向 Map 中添加键值对
                                    keyMap.put("basicInfo", tempTemplate_type);
                                    keyMap.put("logInfo", "logInfo");
                                    keyMap.put("application", "application");
                                    keyMap.put("description", "description");

                                    for (String key : keyMap.keySet()) {
                                        String value = keyMap.get(key);

                                        List<Map<String, Object>> listBasicInfo = new ArrayList<>();

                                        String finalTempTemplate_type = tempTemplate_type;

                                        List<TbTaskTemplateData> filteredList = listTaskTemplateData.stream()
                                                .filter(TbTaskTemplateData -> Objects.equals(TbTaskTemplateData.getParent_param_key(), value))
                                                .collect(Collectors.toList());

                                        if (filteredList != null && !filteredList.isEmpty()) {
                                            // 找到最大 row_sort 值
                                            Optional<Integer> maxRowSort = filteredList.stream()
                                                    .map(TbTaskTemplateData::getRow_sort)
                                                    .filter(Objects::nonNull) // 过滤掉 null 值
                                                    .max(Integer::compareTo);

                                            int maxRowSortValue = maxRowSort.orElse(-1);

                                            for (int i = 0; i <= maxRowSortValue; i++) {
                                                Map<String, Object> basicInfo = new HashMap<>();
                                                for (TbTaskTemplateData tbTaskTemplateData : filteredList) {
                                                    if (tbTaskTemplateData.getRow_sort() == i) {
                                                        if (_type.equals("value") && (tbTaskTemplateData.getParam_type() == 2)) {
                                                            Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                    .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbTaskTemplateData.getParam_value()))
                                                                    .findAny();

                                                            if (optionalTbTaskTemplateData.isPresent()) {
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                            } else {
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), "");
                                                            }
                                                        } else if (_type.equals("value") && tbTaskTemplateData.getParam_type() == 5) {
                                                            if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                ObjectMapper mapper = new ObjectMapper();
                                                                JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                List<Object> resultList = new ArrayList<>();

                                                                for (JsonNode node : rootNode) {
                                                                    Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                            .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(node.asText()))
                                                                            .findAny();

                                                                    if (optionalTbTaskTemplateData.isPresent()) {
                                                                        resultList.add(optionalTbTaskTemplateData.get().getParam_name());
                                                                    }
                                                                }
                                                                //String result = resultList.stream()
                                                                //        .map(obj -> obj == null ? "null" : obj.toString()) // 处理 null 并转字符串
                                                                //        .collect(Collectors.joining("\n")); // 用 \n 拼接

                                                                //basicInfo.put(tbTaskTemplateData.getParam_key(), result);
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                            }
                                                        } else if (tbTaskTemplateData.getParam_type() == 3 || tbTaskTemplateData.getParam_type() == 4) {
                                                            if (tbTaskTemplateData.getParam_value() != null) {
                                                                List<String> fileList = Arrays.asList(tbTaskTemplateData.getParam_value().split(","));
                                                                //List<TbKnowledgeBaseFile> aaa=tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);

                                                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                                tbKnowledgeBaseFileList.stream()
                                                                        .filter(file -> file.getFile_type() != null && file.getFile_type() == 4)
                                                                        .forEach(file -> {
                                                                            String base64 = "";
                                                                            if (env.equals("dev")) {
                                                                                base64 = s3UploadFileService.getImageBase64FromUrl(file.getUrl());
                                                                            } else {
                                                                                base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + file.getUrl());
                                                                            }
                                                                            file.setUrl(CommonUtils.base64Prefix() + base64);
                                                                        });

                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), tbKnowledgeBaseFileList);
                                                            } else {
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), tbTaskTemplateData.getParam_value());
                                                            }
                                                        }
                                                        //&& (tbTaskTemplateData.getParam_type() != 2)
                                                        //20251113
                                                        else if (_type.equals("key") && (tbTaskTemplateData.getParam_type() != 1) && now_level >= flowInfo.getFlow_level()) {
                                                            if (tbTaskTemplateData.getParam_type() == 2) {
                                                                Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                        .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbTaskTemplateData.getParam_value()))
                                                                        .findAny();

                                                                if (optionalTbTaskTemplateData.isPresent()) {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                                } else {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), "");
                                                                }
                                                            }
                                                            if (tbTaskTemplateData.getParam_type() == 5) {
                                                                if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                    ObjectMapper mapper = new ObjectMapper();
                                                                    JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                    List<Object> resultList = new ArrayList<>();

                                                                    for (JsonNode node : rootNode) {
                                                                        Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                                .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(node.asText()))
                                                                                .findAny();

                                                                        if (optionalTbTaskTemplateData.isPresent()) {
                                                                            resultList.add(optionalTbTaskTemplateData.get().getParam_name());
                                                                        }
                                                                    }
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                                }
                                                            }
                                                        } else {
                                                            if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                ObjectMapper mapper = new ObjectMapper();
                                                                JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                List<Object> resultList = new ArrayList<>();

                                                                for (JsonNode node : rootNode) {
                                                                    if (node.isTextual()) {
                                                                        resultList.add(node.asText()); // 字符串类型
                                                                    } else if (node.isInt()) {
                                                                        resultList.add(node.asInt()); // 整数类型
                                                                    }
                                                                }
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                            } else {
                                                                basicInfo.put(tbTaskTemplateData.getParam_key(), tbTaskTemplateData.getParam_value());
                                                            }
                                                        }
                                                    }
                                                }
                                                if (!basicInfo.isEmpty()) {
                                                    basicInfo.put("row", i);
                                                    listBasicInfo.add(basicInfo);
                                                }
                                            }
                                            combinedMap.put(key, listBasicInfo);
                                        }
                                    }

                                    //把模板结构也要同步过来
                                    combinedMap.put("tbTemplate", commonService.buildTree3(listTaskTemplateData));
                                    /**
                                     if (_flow_type.equals("device")) {
                                     //增加5个表的数据
                                     combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(_flow_no, 1));
                                     combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(_flow_no, 1));
                                     combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1));
                                     combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(_flow_no, 1));
                                     combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(_flow_no, 1));
                                     }*/

                                    if (_flow_type.equals("device")) {
                                        //20250325  增加查询,先从列表里面把器件编号,封装名称查出来
                                        // 定义动态目标参数集合（可扩展）
                                        Set<String> targetParams = new HashSet<>(Arrays.asList("器件编码", "器件封装"));

                                        // 执行筛选并生成结果映射
                                        Map<String, TbTaskTemplateData> resultMap = listTaskTemplateData.stream()
                                                .filter(item -> targetParams.contains(item.getParam_name()))
                                                .collect(Collectors.toMap(
                                                        TbTaskTemplateData::getParam_name, // Key：param_name值
                                                        Function.identity(),                // Value：对象本身
                                                        (existing, replacement) -> existing // 解决键冲突（保留第一个）
                                                ));

                                        TbTaskTemplateData componentCodeObj = resultMap.get("器件编码");

                                        TbTaskTemplateData packageNameObj = resultMap.get("器件封装");

                                        String Is_dense_comp = "";
                                        String Pastemask_thickness_max = "";
                                        String Pastemask_thickness_min = "";
                                        String Pin_min_pitch = "";

                                        //要先处理封装库的信息,因为VPL有字段来源封装
                                        List<TbFlowCompPkg> tbFlowCompPkgList = new ArrayList<>();

                                        if (packageNameObj != null) {
                                            if (packageNameObj.getParam_value() != null && !packageNameObj.getParam_value().isEmpty()) {
                                                List<vVplPackage> vplPackageList = _vVplPackageDao.getvVplPackage(packageNameObj.getParam_value());
                                                if (vplPackageList != null && vplPackageList.size() > 0) {
                                                    for (vVplPackage source : vplPackageList) {
                                                        TbFlowCompPkg target = new TbFlowCompPkg();

                                                        // 手动映射同名同类型字段
                                                        target.setPkg_name(source.getPkg_name());
                                                        target.setAssembly_type(source.getAssembly_type());
                                                        target.setFoot_num(source.getFoot_num());
                                                        target.setBody_length(source.getBody_length());
                                                        target.setBody_width(source.getBody_width());
                                                        target.setPad_airgap_min(source.getPad_airgap_min());
                                                        target.setPitch_o2c_x(source.getPitch_o2c_x());
                                                        target.setPitch_o2c_y(source.getPitch_o2c_y());
                                                        target.setIs_size_not_fit(source.getIs_size_not_fit());
                                                        target.setIs_grid_design(source.getIs_grid_design());
                                                        target.setIs_twins_design(source.getIs_twins_design());
                                                        target.setIs_special_design(source.getIs_special_design());
                                                        target.setIs_window_open(source.getIs_window_open());
                                                        target.setIs_small_air_gap(source.getIs_small_air_gap());

                                                        Is_dense_comp = source.getIs_dense_comp();
                                                        Pastemask_thickness_max = source.getPastemask_thickness_max();
                                                        Pastemask_thickness_min = source.getPastemask_thickness_min();
                                                        Pin_min_pitch = source.getPin_min_pitch();

                                                        tbFlowCompPkgList.add(target);
                                                    }
                                                }
                                            }
                                        }

                                        if (tbFlowCompPkgList == null || tbFlowCompPkgList.size() <= 0) {
                                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                                            tbFlowCompPkgList.add(tbFlowCompPkg);
                                        }

                                        combinedMap.put("compPkg", tbFlowCompPkgList);

                                        List<TbFlowCompVpl> tbFlowCompVplList = new ArrayList<>();
                                        List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                        //查询VPL表和封装库表
                                        if (componentCodeObj != null) {
                                            if (componentCodeObj.getParam_value() != null && !componentCodeObj.getParam_value().isEmpty()) {
                                                List<vVplPartData> vVplPartDataList = _vVplPartDataDao.getvVplPartDataByCode(componentCodeObj.getParam_value());

                                                if (vVplPartDataList != null && vVplPartDataList.size() > 0) {
                                                    Optional<Double> maxValueComponent_high_max = vVplPartDataList.stream()
                                                            // 过滤空值和空字符串（兼容带空格的无效数据）
                                                            .filter(obj -> obj.getComponent_high_max() != null && !obj.getComponent_high_max().trim().isEmpty())
                                                            // 正则去除单位（支持 MM/mm/Mm/mM 格式）
                                                            .map(obj -> obj.getComponent_high_max().replaceAll("(?i)mm$", ""))
                                                            // 转换为 Double（兼容科学计数法，如 1.5e2）
                                                            .flatMap(s -> {
                                                                try {
                                                                    return Stream.of(Double.parseDouble(s.trim()));
                                                                } catch (NumberFormatException e) {
                                                                    return Stream.empty(); // 忽略无效数值
                                                                }
                                                            })
                                                            // 求最大值
                                                            .max(Double::compare);

                                                    String maxValueComponent_high_max_str = "";

                                                    if (maxValueComponent_high_max.isPresent()) {
                                                        maxValueComponent_high_max_str = maxValueComponent_high_max.get().toString();
                                                    }

                                                    //取第一个对象,转换成CompVpl的对象
                                                    vVplPartData vVplPartDataObj = vVplPartDataList.get(0);

                                                    TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                                    // 将 vVplPartData 对象的属性值复制到 tbFlowCompVpl 对象中
                                                    // 这里假设 TbFlowCompVpl 类有相应的 setter 方法
                                                    tbFlowCompVpl.setFlow_no(vVplPartDataObj.getCode());
                                                    tbFlowCompVpl.setFlow_level(1);
                                                    tbFlowCompVpl.setComp_code(vVplPartDataObj.getCode());
                                                    tbFlowCompVpl.setComp_type(vVplPartDataObj.getComp_type());
                                                    tbFlowCompVpl.setPkg_name(vVplPartDataObj.getPkg_name());
                                                    tbFlowCompVpl.setAssembly_type(vVplPartDataObj.getAssembly_type());
                                                    tbFlowCompVpl.setComponent_high_max_vpl(maxValueComponent_high_max_str);
                                                    tbFlowCompVpl.setPin_high_max(vVplPartDataObj.getPin_high_max());
                                                    tbFlowCompVpl.setPin_high_min(vVplPartDataObj.getPin_high_min());
                                                    tbFlowCompVpl.setPth_diameter_min(vVplPartDataObj.getPth_diameter_min());
                                                    tbFlowCompVpl.setIs_tht_power(vVplPartDataObj.getIs_tht_power());
                                                    tbFlowCompVpl.setIs_tht_capcitor(vVplPartDataObj.getIs_tht_capcitor());
                                                    tbFlowCompVpl.setIs_glue(vVplPartDataObj.getIs_glue());
                                                    tbFlowCompVpl.setIs_little_retentionforce(vVplPartDataObj.getIs_little_retentionforce());
                                                    //数据在封装里面
                                                    tbFlowCompVpl.setIs_dense_comp(Is_dense_comp);
                                                    tbFlowCompVpl.setPastemask_thickness_max(Pastemask_thickness_max);
                                                    tbFlowCompVpl.setPastemask_thickness_min(Pastemask_thickness_min);
                                                    tbFlowCompVpl.setPin_min_pitch(Pin_min_pitch);

                                                    // 将转换后的 TbFlowCompVpl 对象添加到列表中
                                                    tbFlowCompVplList.add(tbFlowCompVpl);

                                                    for (vVplPartData source : vVplPartDataList) {
                                                        TbFlowCompManufacturer target = new TbFlowCompManufacturer();

                                                        // 映射同名同类型字段
                                                        target.setManufacturer(source.getManufacturer());
                                                        target.setManufacturer_type(source.getManufacturer_type());
                                                        target.setWeight(source.getWeight());
                                                        target.setCoplanarity(source.getCoplanarity());
                                                        target.setStandoff(source.getStandoff());
                                                        target.setSolder_tg_max(source.getSolder_tg_max());
                                                        target.setBga_height_min(source.getBga_height_min());
                                                        target.setUnbd_thickness_min(source.getUnbd_thickness_min());
                                                        target.setBoard_thickness_min(source.getBoard_thickness_min());
                                                        target.setBoard_thickness_max(source.getBoard_thickness_max());
                                                        target.setIs_secd_reflow_drop(source.getIs_secd_reflow_drop());
                                                        tbFlowCompManufacturerList.add(target);
                                                    }
                                                }
                                            }
                                        }

                                        if (tbFlowCompVplList == null || tbFlowCompVplList.size() <= 0) {
                                            TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                            tbFlowCompVplList.add(tbFlowCompVpl);
                                        }

                                        //if(tbFlowCompManufacturerList==null ||tbFlowCompManufacturerList.size()<=0)
                                        //{
                                        //    TbFlowCompManufacturer tbFlowCompManufacturer=new TbFlowCompManufacturer();
                                        //    tbFlowCompManufacturerList.add(tbFlowCompManufacturer);
                                        //}


                                        combinedMap.put("compVpl", tbFlowCompVplList);
                                        combinedMap.put("compManufacturer", tbFlowCompManufacturerList);
                                    }
                                }


                                combinedList.add(combinedMap);
                            }

                            return ResultUtil.success(combinedList);
                        }

                        if (_flow_type.equals("vpl")) {
                            List<TbFlowProcessMain> listFlowProcessMain = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);
                            if (listFlowProcessMain == null || listFlowProcessMain.size() <= 0) {
                                return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                            }

                            TbFlowProcessMain tbFlowProcessMain = listFlowProcessMain.get(0);
                            Integer now_level = tbFlowProcessMain.getNow_level();

                            now_level = _now_level;
                            //if(tbFlowProcessMain.getStatus()==3)
                            //{
                            //    now_level=9999;
                            //}

                            List<TbTaskVersion> listTaskVersion = tbTaskVersionDao.getTaskVersionByFlowNo(_flow_no);
                            if (listTaskVersion == null || listTaskVersion.size() <= 0) {
                                return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                            }

                            TbTaskVersion tbTaskVersion = listTaskVersion.get(0);

                            List<TbFlowProcessDetail> listFlowProcessDetail = tbFlowProcessDetailDao.getFlowDetailsByFlowNo(_flow_no);

                            if (listFlowProcessDetail == null || listFlowProcessDetail.size() <= 0) {
                                return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                            }


                            List<Map<String, Object>> combinedList = new ArrayList<>();

                            for (TbFlowProcessDetail flowInfo : listFlowProcessDetail) {
                                Map<String, Object> combinedMap = new HashMap<>();
                                combinedMap.put("id", flowInfo.getId());
                                combinedMap.put("flow_type", flowInfo.getFlow_type());
                                combinedMap.put("flow_name", flowInfo.getFlow_name());
                                combinedMap.put("flow_level", flowInfo.getFlow_level());
                                combinedMap.put("knowledge_base_key", tbFlowProcessMain.getKnowledge_base_key());
                                combinedMap.put("flow_approver", flowInfo.getFlow_approver());
                                combinedMap.put("sort", flowInfo.getSort());
                                //combinedMap.put("create_time", flowInfo.getCreate_time());
                                combinedMap.put("create_user", flowInfo.getCreate_user());
                                combinedMap.put("is_skip", flowInfo.getIs_skip());
                                try {
                                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    combinedMap.put("create_time", sfd.format(flowInfo.getCreate_time()));
                                } catch (Exception e) {
                                    combinedMap.put("create_time", flowInfo.getCreate_time());
                                }

                                try {
                                    SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    combinedMap.put("update_time", sfd.format(flowInfo.getUpdate_time()));
                                } catch (Exception e) {
                                    combinedMap.put("update_time", flowInfo.getUpdate_time());
                                }
                                combinedMap.put("update_user", flowInfo.getUpdate_user());
                                combinedMap.put("remark", flowInfo.getRemark());
                                combinedMap.put("status", flowInfo.getStatus());
                                String flowApprovers = flowInfo.getFlow_approver();
                                if (flowApprovers != null && !flowApprovers.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));

                                    combinedMap.put("flow_approver_list", flowApproverList);
                                    combinedMap.put("flow_approver_info", user2Dao.getUserInfoByIds(flowApproverList));
                                }

                                combinedMap.put("flow_approver_authorize", flowInfo.getFlow_approver_authorize());
                                combinedMap.put("comments", flowInfo.getComments());
                                combinedMap.put("designer", flowInfo.getDesigner());

                                String designer = flowInfo.getDesigner();
                                if (designer != null && !designer.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> designerList = Arrays.asList(designer.split(","));

                                    combinedMap.put("designer_info", user2Dao.getUserInfoByIds(designerList));
                                } else {
                                    combinedMap.put("designer_info", null);
                                }

                                String vpl_create_user = flowInfo.getVpl_create_user();
                                if (vpl_create_user != null && !vpl_create_user.isEmpty()) {

                                    List<String> vpl_create_userList = Arrays.asList(vpl_create_user.split(","));

                                    //combinedMap.put("vpl_create_user_list", vpl_create_userList);
                                    combinedMap.put("vpl_create_user_info", user2Dao.getUserInfoByIds(vpl_create_userList));
                                } else {
                                    combinedMap.put("vpl_create_user_info", null);
                                }
                                combinedMap.put("vpl_create_user", vpl_create_user);

                                Integer flowLevel = flowInfo.getFlow_level();

                                if (flowLevel == 1) {
                                    combinedMap.put("other_resource", flowInfo.getOther_resource());
                                    combinedMap.put("cc", flowInfo.getCc());

                                    String other_resource_files = flowInfo.getOther_resource_files();
                                    if (other_resource_files != null && !other_resource_files.isEmpty()) {
                                        List<String> fileList = Arrays.asList(other_resource_files.split(","));
                                        combinedMap.put("other_resource_files_list", tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList));
                                    } else {
                                        combinedMap.put("other_resource_files_list", null);
                                    }
                                    combinedMap.put("other_resource_files", other_resource_files);


                                    String cc = flowInfo.getCc();
                                    if (cc != null && !cc.isEmpty()) {

                                        List<String> ccList = Arrays.asList(cc.split(","));

                                        combinedMap.put("cc_list", ccList);
                                        combinedMap.put("cc_info", user2Dao.getUserInfoByIds(ccList));
                                    } else {
                                        combinedMap.put("cc_list", null);
                                        combinedMap.put("cc_info", null);
                                    }
                                    //获取TbFlowCompVplPdm和TbFlowCompManifacturer的数据
                                    combinedMap.put("compVplPdm", tbFlowCompVplPdmDao.getTbFlowCompVplPdmByFlowNo(_flow_no, flowLevel));

                                    List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                    tbFlowCompManufacturerList = tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, flowLevel);

                                    if (tbFlowCompManufacturerList != null && tbFlowCompManufacturerList.size() > 0) {
                                        //循环list去查找文件信息
                                        for (TbFlowCompManufacturer tbFlowCompManufacturer : tbFlowCompManufacturerList) {
                                            String comp_resource = tbFlowCompManufacturer.getComp_resource();
                                            if (comp_resource != null && !comp_resource.isEmpty()) {
                                                List<String> fileList = Arrays.asList(comp_resource.split(","));

                                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                tbFlowCompManufacturer.setComp_resource_list(tbKnowledgeBaseFileList);
                                            } else {
                                                tbFlowCompManufacturer.setComp_resource_list(null);
                                            }
                                        }
                                    }

                                    combinedMap.put("compManufacturer", tbFlowCompManufacturerList);
                                }
                                if (flowLevel == 2) {
                                    String supply_vpl_create_user = flowInfo.getSupply_vpl_create_user();
                                    if (supply_vpl_create_user != null && !supply_vpl_create_user.isEmpty()) {

                                        List<String> supply_vpl_create_userList = Arrays.asList(supply_vpl_create_user.split(","));
                                        combinedMap.put("supply_vpl_create_user_info", user2Dao.getUserInfoByIds(supply_vpl_create_userList));
                                    }
                                    combinedMap.put("supply_vpl_create_user", supply_vpl_create_user);

                                    combinedMap.put("difficulty", flowInfo.getDifficulty());
                                    combinedMap.put("equivalent_num", flowInfo.getEquivalent_num());
                                    combinedMap.put("vpl_finish_time", flowInfo.getVpl_finish_time());

                                    String vpl_attr_excel = flowInfo.getVpl_attr_excel();
                                    if (vpl_attr_excel != null && !vpl_attr_excel.isEmpty()) {
                                        combinedMap.put("vpl_attr_excel_list", tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParamKey(vpl_attr_excel));
                                    }
                                    combinedMap.put("vpl_attr_excel", flowInfo.getVpl_attr_excel());
                                    String vpl_model_excel = flowInfo.getVpl_model_excel();
                                    if (vpl_model_excel != null && !vpl_model_excel.isEmpty()) {
                                        combinedMap.put("vpl_model_excel_list", tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParamKey(vpl_model_excel));
                                    }
                                    combinedMap.put("vpl_model_excel", flowInfo.getVpl_model_excel());

                                    combinedMap.put("max_Body_height", flowInfo.getMax_Body_height());
                                    combinedMap.put("max_Pin_length", flowInfo.getMax_Pin_length());
                                    combinedMap.put("min_Pin_length", flowInfo.getMin_Pin_length());

                                    //获取vpl数据
                                    List<vVplPartData> vVplPartDataList = new ArrayList<>();
                                    vVplPartDataList = _vVplPartDataDao.getvVplPartDataAll();

                                    List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                    tbFlowCompManufacturerList = tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1);

                                    if (tbFlowCompManufacturerList != null && tbFlowCompManufacturerList.size() > 0) {
                                        if (vVplPartDataList != null && vVplPartDataList.size() > 0) {
                                            List<vVplPartData> finalVVplPartDataList = vVplPartDataList;
                                            tbFlowCompManufacturerList.forEach(tb -> {
                                                if (tb == null) {
                                                    tb.setIs_vpl_created("否");
                                                } else {
                                                    List<vVplPartData> vplPartDataList = _vVplPartDataDao.getvVplPartData(tbTaskVersion.getComp_code(), tb.getManufacturer_type());

                                                    if (vplPartDataList != null && vplPartDataList.size() > 0) {
                                                        tb.setIs_vpl_created("是");
                                                    } else {
                                                        tb.setIs_vpl_created("否");
                                                    }
                                                }
                                            });

                                        }
                                    }

                                    combinedMap.put("compManufacturer", tbFlowCompManufacturerList);
                                    combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(_flow_no, flowLevel));
                                    combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(_flow_no, flowLevel));
                                }
                                if (flowLevel == 3) {

                                    String vpl_pkg_excel = flowInfo.getVpl_pkg_excel();
                                    if (vpl_pkg_excel != null && !vpl_pkg_excel.isEmpty()) {
                                        combinedMap.put("vpl_pkg_excel_list", tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParamKey(vpl_pkg_excel));
                                    }
                                    combinedMap.put("vpl_pkg_excel", flowInfo.getVpl_pkg_excel());
                                    combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(_flow_no, flowLevel));
                                }

                                // 判断是否添加 basicInfo
                                if (flowInfo.getFlow_level() == 4) {
                                    combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(_flow_no, flowLevel));

                                    //1是是,0是否
                                    if (_type.equals("value") && now_level > flowInfo.getFlow_level()) {
                                        List<TbFlowCompManufacturer> tfcmfList = tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1);


                                        for (TbFlowCompManufacturer tfcm : tfcmfList) {
                                            String originalIsOk = tfcm.getIs_secd_reflow_drop(); // 假设原始字段是 Integer 类型
                                            if (originalIsOk != null) {
                                                tfcm.setIs_secd_reflow_drop(originalIsOk.equals("1") ? "是" : "否");
                                            }
                                        }

                                        combinedMap.put("compManufacturer", tfcmfList);
                                    } else {
                                        combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1));
                                    }


                                    combinedMap.put("is_vpl_parameters_checked", flowInfo.getIs_vpl_parameters_checked());
                                    combinedMap.put("is_need_knowledge_base", flowInfo.getIs_need_knowledge_base());

                                    //获取数据库现在所有的条目信息
                                    List<TbTaskTemplateData> listTaskTemplateData = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(_flow_no);
                                    if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                                        combinedMap.put("tbTemplate", commonService.buildTree3(listTaskTemplateData));
                                        //动态模板部分
                                        Map<String, String> keyMap = new HashMap<>();

                                        // 向 Map 中添加键值对
                                        keyMap.put("basicInfo", tempTemplate_type);
                                        keyMap.put("logInfo", "logInfo");
                                        keyMap.put("application", "application");
                                        keyMap.put("description", "description");

                                        for (String key : keyMap.keySet()) {
                                            String value = keyMap.get(key);

                                            List<Map<String, Object>> listBasicInfo = new ArrayList<>();

                                            String finalTempTemplate_type = tempTemplate_type;

                                            List<TbTaskTemplateData> filteredList = listTaskTemplateData.stream()
                                                    .filter(TbTaskTemplateData -> Objects.equals(TbTaskTemplateData.getParent_param_key(), value))
                                                    .collect(Collectors.toList());

                                            if (filteredList != null && !filteredList.isEmpty()) {
                                                // 找到最大 row_sort 值
                                                Optional<Integer> maxRowSort = filteredList.stream()
                                                        .map(TbTaskTemplateData::getRow_sort)
                                                        .filter(Objects::nonNull) // 过滤掉 null 值
                                                        .max(Integer::compareTo);

                                                int maxRowSortValue = maxRowSort.orElse(-1);

                                                for (int i = 0; i <= maxRowSortValue; i++) {
                                                    Map<String, Object> basicInfo = new HashMap<>();
                                                    for (TbTaskTemplateData tbTaskTemplateData : filteredList) {
                                                        if (tbTaskTemplateData.getRow_sort() == i) {
                                                            if (_type.equals("value") && (tbTaskTemplateData.getParam_type() == 2)) {
                                                                Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                        .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbTaskTemplateData.getParam_value()))
                                                                        .findAny();

                                                                if (optionalTbTaskTemplateData.isPresent()) {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                                } else {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), "");
                                                                }
                                                            } else if (_type.equals("value") && tbTaskTemplateData.getParam_type() == 5) {
                                                                if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                    ObjectMapper mapper = new ObjectMapper();
                                                                    JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                    List<Object> resultList = new ArrayList<>();

                                                                    for (JsonNode node : rootNode) {
                                                                        Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                                .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(node.asText()))
                                                                                .findAny();

                                                                        if (optionalTbTaskTemplateData.isPresent()) {
                                                                            resultList.add(optionalTbTaskTemplateData.get().getParam_name());
                                                                        }
                                                                    }

                                                                    //String result = resultList.stream()
                                                                    //        .map(obj -> obj == null ? "null" : obj.toString()) // 处理 null 并转字符串
                                                                    //        .collect(Collectors.joining("\n")); // 用 \n 拼接
//
                                                                    //basicInfo.put(tbTaskTemplateData.getParam_key(), result);
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                                }
                                                            } else if (tbTaskTemplateData.getParam_type() == 3 || tbTaskTemplateData.getParam_type() == 4) {
                                                                if (tbTaskTemplateData.getParam_value() != null) {
                                                                    List<String> fileList = Arrays.asList(tbTaskTemplateData.getParam_value().split(","));
                                                                    //basicInfo.put(tbTaskTemplateData.getParam_key(), tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList));
                                                                    List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                                    tbKnowledgeBaseFileList.stream()
                                                                            .filter(file -> file.getFile_type() != null && file.getFile_type() == 4)
                                                                            .forEach(file -> {
                                                                                String base64 = "";
                                                                                if (env.equals("dev")) {
                                                                                    base64 = s3UploadFileService.getImageBase64FromUrl(file.getUrl());
                                                                                } else {
                                                                                    base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + file.getUrl());
                                                                                }
                                                                                file.setUrl(CommonUtils.base64Prefix() + base64);
                                                                            });

                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), tbKnowledgeBaseFileList);
                                                                } else {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), tbTaskTemplateData.getParam_value());
                                                                }
                                                            } else if (_type.equals("key") && (tbTaskTemplateData.getParam_type() != 1) && now_level >= flowInfo.getFlow_level()) {
                                                                //Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                //        .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbTaskTemplateData.getParam_value()))
                                                                //        .findAny();
                                                                //if (optionalTbTaskTemplateData.isPresent()) {
                                                                //    basicInfo.put(tbTaskTemplateData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                                //} else {
                                                                //    basicInfo.put(tbTaskTemplateData.getParam_key(), "");
                                                                //}

                                                                if (tbTaskTemplateData.getParam_type() == 2) {
                                                                    Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                            .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbTaskTemplateData.getParam_value()))
                                                                            .findAny();

                                                                    if (optionalTbTaskTemplateData.isPresent()) {
                                                                        basicInfo.put(tbTaskTemplateData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                                    } else {
                                                                        basicInfo.put(tbTaskTemplateData.getParam_key(), "");
                                                                    }
                                                                }
                                                                if (tbTaskTemplateData.getParam_type() == 5) {
                                                                    if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                        ObjectMapper mapper = new ObjectMapper();
                                                                        JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                        List<Object> resultList = new ArrayList<>();

                                                                        for (JsonNode node : rootNode) {
                                                                            Optional<TbTaskTemplateData> optionalTbTaskTemplateData = listTaskTemplateData.stream()
                                                                                    .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(node.asText()))
                                                                                    .findAny();

                                                                            if (optionalTbTaskTemplateData.isPresent()) {
                                                                                resultList.add(optionalTbTaskTemplateData.get().getParam_name());
                                                                            }
                                                                        }
                                                                        basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                                    }
                                                                }
                                                            } else {

                                                                if (tbTaskTemplateData.getParam_value() != null && tbTaskTemplateData.getParam_value().startsWith("[")) {
                                                                    ObjectMapper mapper = new ObjectMapper();
                                                                    JsonNode rootNode = mapper.readTree(tbTaskTemplateData.getParam_value());
                                                                    List<Object> resultList = new ArrayList<>();

                                                                    for (JsonNode node : rootNode) {
                                                                        if (node.isTextual()) {
                                                                            resultList.add(node.asText()); // 字符串类型
                                                                        } else if (node.isInt()) {
                                                                            resultList.add(node.asInt()); // 整数类型
                                                                        }
                                                                    }
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), resultList);
                                                                } else {
                                                                    basicInfo.put(tbTaskTemplateData.getParam_key(), tbTaskTemplateData.getParam_value());
                                                                }
                                                                //basicInfo.put(tbTaskTemplateData.getParam_key(), tbTaskTemplateData.getParam_value());
                                                            }
                                                        }
                                                    }
                                                    if (!basicInfo.isEmpty()) {
                                                        basicInfo.put("row", i);
                                                        listBasicInfo.add(basicInfo);
                                                    }
                                                }
                                                combinedMap.put(key, listBasicInfo);
                                            }
                                        }
                                    } else {
                                        combinedMap.put("tbTemplate", "");
                                    }
                                }

                                //20250904增加一个判断,canEditPkg
                                if (flowInfo.getFlow_level() == 3) {
                                    String canEditPkg = "N";
                                    //判断第一个节点里面的PDM封装是不是空的.如果是空的,那么canEditPkg为Y
                                    List<TbFlowCompVplPdm> listPdm = tbFlowCompVplPdmDao.getTbFlowCompVplPdmByFlowNo(_flow_no, 1);
                                    if (listPdm != null && listPdm.size() > 0) {
                                        TbFlowCompVplPdm tcvp = listPdm.get(0);
                                        if (tcvp.getS1PCBENCPFILENAME() == null || tcvp.getS1PCBENCPFILENAME().isEmpty()) {
                                            canEditPkg = "Y";
                                        } else {
                                            //不是空的话,判断一下是不是来自于VPL,如果不是那么canEditPkg为Y
                                            List<TbFlowCompPkg> tfcp = tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(_flow_no, 3);
                                            if (tfcp != null && tfcp.size() > 0) {
                                                TbFlowCompPkg tcpp = tfcp.get(0);
                                                if (tcpp.getIs_from_vpl() == null || tcpp.getIs_from_vpl().isEmpty() || !tcpp.getIs_from_vpl().equalsIgnoreCase("Y")) {
                                                    canEditPkg = "Y";
                                                }
                                            }
                                        }
                                    } else {
                                        canEditPkg = "Y";
                                    }

                                    combinedMap.put("canEditPkg", canEditPkg);
                                }

                                combinedList.add(combinedMap);
                            }

                            return ResultUtil.success(combinedList);
                        }
                    } else {
                        //先判断是否取到了标准流程的流程节点信息
                        List<TbFlowDetail> tbFlowDetails = tbFlowDetailDao.getFolwListByType(_flow_type);
                        if (tbFlowDetails == null || tbFlowDetails.size() <= 0) {
                            return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                        }

                        if (_flow_type.equals("design") || _flow_type.equals("device")) {
                            //设计流程的第一个节点是获取模板信息
                            //获取最新版本的版本号
                            List<TbTemplateVersion> list = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplate_type);

                            List<TbTemplate> templateList = new ArrayList<>();

                            if (list != null && list.size() > 0) {
                                String _version = list.get(0).getVersion();
                                List<TbTemplate> listResult = tbTemplateDao.getPublishedTbTemplateByVersion(tempTemplate_type, _version);

                                templateList = commonService.buildTree2(listResult);

                                if (templateList == null || templateList.size() <= 0) {
                                    return ResultUtil.error(500, "没有找到该模板类型", "", null);
                                }

                            } else {
                                return ResultUtil.error(500, "没有找到该模板已分发的版本", "", null);
                            }

                            tbFlowDetails.get(0).setTbTemplate(templateList);

                            for (TbFlowDetail detail : tbFlowDetails) {
                                String flowApprovers = detail.getFlow_approver();
                                if (flowApprovers != null && !flowApprovers.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));
                                    detail.setFlow_approver_list(flowApproverList);
                                    detail.setFlow_approver_info(user2Dao.getUserInfoByIds(flowApproverList));
                                }
                            }

                            return ResultUtil.success(tbFlowDetails);
                        }

                        if (_flow_type.equals("vpl")) {

                            List<TbTemplateVersion> list = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplate_type);

                            List<TbTemplate> templateList = new ArrayList<>();

                            if (list != null && list.size() > 0) {
                                String _version = list.get(0).getVersion();
                                List<TbTemplate> listResult = tbTemplateDao.getPublishedTbTemplateByVersion(tempTemplate_type, _version);

                                templateList = commonService.buildTree2(listResult);

                                if (templateList == null || templateList.size() <= 0) {
                                    return ResultUtil.error(500, "没有找到该模板类型", "", null);
                                }

                            } else {
                                return ResultUtil.error(500, "没有找到该模板已分发的版本", "", null);
                            }

                            tbFlowDetails.get(3).setTbTemplate(templateList);

                            for (TbFlowDetail detail : tbFlowDetails) {
                                String flowApprovers = detail.getFlow_approver();
                                if (flowApprovers != null && !flowApprovers.isEmpty()) {
                                    // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                                    List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));
                                    detail.setFlow_approver_list(flowApproverList);
                                    detail.setFlow_approver_info(user2Dao.getUserInfoByIds(flowApproverList));
                                }
                            }

                            return ResultUtil.success(tbFlowDetails);
                        }
                    }

                    return ResultUtil.success("处理成功");
                } else {
                    return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    //@Transactional(transactionManager = "MysqlTransactionManager7")
    @Override
    public Result operateTaskFlow(String data) {

        try {
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObjectB = JSONObject.parseObject(data);

                // 获取application和description的JSONArray
                JSONArray applicationArray = jsonObjectB.getJSONArray("application");
                JSONArray descriptionArray = jsonObjectB.getJSONArray("description");

                // 如果application和description的JSONArray不为空，就删除最后一个元素
                if (applicationArray != null && applicationArray.size() > 0) {
                    applicationArray.remove(applicationArray.size() - 1);
                }
                if (descriptionArray != null && descriptionArray.size() > 0) {
                    descriptionArray.remove(descriptionArray.size() - 1);
                }

                String newJson = jsonObjectB.toString();

                JSONObject jsonObject = JSONObject.parseObject(newJson);

                //操作类型,区别在与是否修改状态
                //save 保存数据
                //commit 提交数据
                String _type = jsonObject.getString("type");
                String _flow_type = jsonObject.getString("flow_type");
                String _flow_no = jsonObject.getString("flow_no");
                //20250324增加判断,在第四个节点的时候,会有一个字段is_need_knowledge_base
                Integer _flow_level = jsonObject.getInteger("flow_level");
                //0是false,1ture
                Integer _is_need_knowledge_base = jsonObject.getInteger("is_need_knowledge_base");
                boolean is_need_knowledge_base = true;

                if (_flow_type.equals("vpl") && (_is_need_knowledge_base == null || _is_need_knowledge_base == 0)) {
                    is_need_knowledge_base = false;
                }

                //20250320 修改流程创建逻辑,新增知识库的key值获取
                //vpl流程只有在第四个节点的时候才会有这个数据出现
                //device和design 会在第一个阶段有数据
                //所以这里需要判断一下

                if (_type == null || (!_type.equals("save") && !_type.equals("commit"))) {
                    return ResultUtil.error(500, "type 只支持save&commit", "", null);
                }
                //if (_type.equals("commit") && (_flow_no == null || _flow_no.isEmpty())) {
                //return ResultUtil.error(500, "提交数据时,flow_no不能为空", "", null);
                //}
                //限制模板类型
                if (!_flow_type.equals("device") && !_flow_type.equals("design") && !_flow_type.equals("vpl")) {
                    return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                }
                String tempTemplateName = "";
                if (_flow_type.equals("design")) {
                    tempTemplateName = "designType";
                }

                if (_flow_type.equals("device") || _flow_type.equals("vpl")) {
                    tempTemplateName = "deviceType";
                }

                if (_type.equals("save")) {
                    //新建数据状态
                    if (_flow_no == null || _flow_no.isEmpty()) {
                        /** 原始方法备份
                         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                         String currentDate = sdf.format(new Date());
                         TbFlowProcessMain byFlowNo = tbFlowProcessMainDao.getByFlowNo(currentDate);
                         int currentSeq = 0;
                         if (byFlowNo != null) {
                         currentSeq = byFlowNo.getSeq();
                         }
                         currentSeq++;
                         //流程编号
                         _flow_no = currentDate + String.format("%05d", currentSeq);
                         String version = UUID.randomUUID().toString();
                         //获取审核流程
                         List<TbFlowDetail> listFlow = tbFlowDetailDao.getFolwListByType(_flow_type);
                         //写入审核流程信息
                         List<TbFlowProcessDetail> listFlowTemplate = new ArrayList<>();
                         for (TbFlowDetail flow : listFlow) {
                         listFlowTemplate.add(new TbFlowProcessDetail(
                         _flow_no,
                         flow.flow_type,
                         flow.flow_name,
                         flow.flow_level,
                         flow.flow_approver,
                         1,
                         flow.sort,
                         UserHeaderHolder.getUserId(),
                         new Date()));
                         }
                         //获取当前流程的第一个对象
                         TbFlowProcessDetail firstFlowProcessDetail = listFlowTemplate.get(0);
                         //获取前端传过来的信息授权信息
                         if (jsonObject.containsKey("flowInfo"))
                         {
                         String comments = jsonObject.getJSONObject("flowInfo").getString("comments");
                         String flowApprover = jsonObject.getJSONObject("flowInfo").getString("flow_approver");
                         String designer = jsonObject.getJSONObject("flowInfo").getString("designer");

                         firstFlowProcessDetail.setComments(comments);
                         firstFlowProcessDetail.setFlow_approver(flowApprover);
                         firstFlowProcessDetail.setDesigner(designer);
                         }
                         listFlowTemplate.set(0, firstFlowProcessDetail);
                         //TbFlowDetail firstFlow = listFlow.get(0);

                         //写入主表信息
                         TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                         tbFlowProcessMain.setFlow_no(_flow_no);
                         tbFlowProcessMain.setFlow_type(_flow_type);
                         tbFlowProcessMain.setSeq(currentSeq);
                         tbFlowProcessMain.setNow_level(firstFlowProcessDetail.getFlow_level());
                         tbFlowProcessMain.setNow_approver(firstFlowProcessDetail.getFlow_approver());
                         tbFlowProcessMain.setStatus(4);
                         tbFlowProcessMain.setCreate_time(new Date());
                         tbFlowProcessMain.setCreate_user(UserHeaderHolder.getUserId());

                         Integer _sort = 1;
                         List<TbTaskVersion> listTaskVersion = tbTaskVersionDao.getNewestTaskVersion(_flow_type);
                         if (listTaskVersion != null && listTaskVersion.size() > 0) {
                         TbTaskVersion tbTaskVersion = listTaskVersion.get(0);
                         _sort = tbTaskVersion.getSort() + 1;

                         }
                         TbTaskVersion tbTaskVersion = new TbTaskVersion();
                         tbTaskVersion.setVersion(version);
                         tbTaskVersion.setTask_type(_flow_type);
                         tbTaskVersion.setCreate_user(UserHeaderHolder.getUserId());
                         tbTaskVersion.setCreate_time(new Date());
                         tbTaskVersion.setSort(_sort);
                         tbTaskVersion.setFlow_no(_flow_no);
                         tbTaskVersion.setStatus(1);

                         if(_flow_type.equals("design"))
                         {
                         List<TbTaskTemplateData> resultList = new ArrayList<>();
                         //处理版本明细表数据
                         if (!tempTemplateName.isEmpty())
                         {
                         List<TbTemplateVersion> listVersion = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplateName);

                         if (listVersion != null && listVersion.size() > 0)
                         {
                         TbTemplateVersion tbTemplateVersion = listVersion.get(0);

                         List<TbTemplate> listTemplate = tbTemplateDao.getTbTemplateByVersion(tempTemplateName, tbTemplateVersion.getVersion());
                         if (listTemplate != null && listTemplate.size() > 0) {
                         //先转成TbTaskTemplateData
                         String final_flow_no = _flow_no;

                         List<TbTaskTemplateData> listTaskTemplateData = listTemplate.stream()
                         .map(template -> {
                         TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                         taskTemplateData.setFlow_no(final_flow_no);
                         taskTemplateData.setFlow_level(1);
                         taskTemplateData.setVersion(template.getVersion());
                         taskTemplateData.setTemplate_type(template.getTemplate_type());
                         taskTemplateData.setParent_id(template.getParent_id());
                         taskTemplateData.setParam_name(template.getParam_name());
                         taskTemplateData.setParam_name_en(template.getParam_name_en());
                         taskTemplateData.setParam_key(template.getParam_key());
                         taskTemplateData.setParent_param_key(template.getParent_param_key());
                         taskTemplateData.setParam_type(template.getParam_type());
                         taskTemplateData.setLevel(template.getLevel());
                         taskTemplateData.setSelect_level(template.getSelect_level());
                         taskTemplateData.setParent_select_id(template.getParent_select_id());
                         taskTemplateData.setTip(template.getTip());
                         taskTemplateData.setRemark(template.getRemark());
                         taskTemplateData.setSort(template.getSort());
                         taskTemplateData.setIs_value(template.getIs_value());
                         return taskTemplateData;
                         })
                         //.filter(taskTemplateData -> taskTemplateData.getIs_value() == 2)
                         .collect(Collectors.toList());

                         if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                         resultList = getValuesFromJson("",jsonObject, listTaskTemplateData);
                         } else {
                         return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                         }
                         } else {
                         return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                         }

                         }
                         else
                         {
                         return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                         }
                         }
                         else
                         {
                         return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                         }
                         //写入明细数据表
                         tbTaskTemplateDataDao.insertTaskTemplateDataBatch(resultList);
                         }

                         //流程主表
                         tbFlowProcessMainDao.insertFlowProcessMain(tbFlowProcessMain);
                         //流程明细表
                         tbFlowProcessDetailDao.insertFlowTemplateBatch(listFlowTemplate);
                         //版本主表
                         tbTaskVersionDao.insertTaskVersion(tbTaskVersion);


                         return ResultUtil.success(_flow_no);
                         */

                        return handleAdd(_flow_type, jsonObject, tempTemplateName, null, "create");
                    }
                    //修改对应流程信息
                    else {
                        /**
                         List<TbTaskTemplateData> resultList = new ArrayList<>();
                         //处理版本明细表数据

                         //先转成TbTaskTemplateData
                         String final_flow_no = _flow_no;

                         List<TbTaskTemplateData> listTaskTemplateData = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(final_flow_no);

                         if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                         resultList = getValuesFromJson(jsonObject, listTaskTemplateData);
                         } else {
                         return ResultUtil.error(500, "未查询到该流程数据", "", null);
                         }

                         //处理好数据以后就是更新数据
                         resultList.forEach(entity -> {
                         Integer tempIsAdd=entity.getIs_Add();

                         entity.setUpdate_time(new Date());
                         entity.setUpdate_user(UserHeaderHolder.getUserId());
                         if (tempIsAdd==null||entity.getIs_Add() == 1) {

                         tbTaskTemplateDataDao.updateTaskTemplateData(entity);
                         }

                         if (tempIsAdd!=null&&entity.getIs_Add() == 0)
                         {
                         List<TbTaskTemplateData> listAdd=new ArrayList<>();
                         entity.setCreate_time(new Date());
                         entity.setCreate_user(UserHeaderHolder.getUserId());
                         listAdd.add(entity);

                         tbTaskTemplateDataDao.insertTaskTemplateDataBatch(listAdd);
                         }
                         });

                         return ResultUtil.success(_flow_no);
                         */

                        handleUpdateFlow(_flow_no, jsonObject, _type, _flow_type);

                        return handleUpdateAndCommit(_flow_no, jsonObject, _type, _flow_type, is_need_knowledge_base, true, true, "Y");
                    }
                } else if (_type.equals("commit")) {
                    //相当于是审批流程
                    //还要更新保存的信息
                    if (_flow_no != null && !_flow_no.isEmpty()) {
                        //handleUpdateFlow(_flow_no, jsonObject, _type, _flow_type);

                        //20250324 新加一个判断如果是vpl的第四个节点的话,可以直接归档
                        if (_flow_type.equals("vpl") && _flow_level == 4 && !is_need_knowledge_base) {
                            return vplSkipNode4(data, _flow_no, jsonObject, _type, _flow_type, is_need_knowledge_base);
                        } else {
                            return handleUpdateAndCommit(_flow_no, jsonObject, _type, _flow_type, is_need_knowledge_base, true, true, "Y");
                        }


                    } else {
                        Result r1 = handleAdd(_flow_type, jsonObject, tempTemplateName, null, "create");

                        if (r1.getCode() != 200) {
                            return r1;
                        }

                        _flow_no = r1.getData().toString();

                        return handleUpdateAndCommit(_flow_no, jsonObject, _type, _flow_type, is_need_knowledge_base, true, false, "N");
                    }
                    //return ResultUtil.success("功能未完成");
                } else {
                    return ResultUtil.error(500, "参数错误", "", null);
                }
            } else {

                return ResultUtil.error(500, "参数为空", "", null);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result returnToPreNode(String data) {

        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _flow_no = jsonObject.getString("flow_no");
                Integer _flow_level = jsonObject.getInteger("flow_level");
                String comments = jsonObject.getString("comments");

                //参数都不能为空
                if (_flow_no == null || _flow_no.isEmpty()) {
                    return ResultUtil.error(500, "flow_no不可以为空", "", null);
                }

                if (_flow_level == null) {
                    return ResultUtil.error(500, "flow_level不可以为空", "", null);
                }

                //获取一下当前流程的主信息
                TbFlowProcessMain param = new TbFlowProcessMain();
                param.setFlow_no(_flow_no);

                List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMain(param);
                if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                    TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);

                    Integer _flow_status = tbFlowProcessMain.getStatus();
                    //1 待审核 2审核中 3审核完成 4草稿
                    if (_flow_status == 3) {
                        return ResultUtil.error(500, "该流程已审核完成", "", null);
                    } else {
                        //获取当前所在节点
                        String _flow_type = tbFlowProcessMain.getFlow_type();
                        Integer _now_level = tbFlowProcessMain.getNow_level();

                        //去查询是否有下一个节点,正常是不会为空的,为空就说明就成结束了.但是加上个非空判断吧
                        if (_now_level != null) {
                            Integer toLevel=_now_level - 1;
                            //20250918 修改逻辑 增加跳过节点,直接到指定节点
                            if(_flow_type!=null&&_flow_type.equals("vpl")&&_now_level==4)
                            {
                                //去获取一下第一个节点的信息过来.
                                TbFlowProcessDetail paramSkip = new TbFlowProcessDetail();
                                paramSkip.setFlow_no(_flow_no);
                                paramSkip.setFlow_type(_flow_type);
                                paramSkip.setFlow_level(1);
                                List<TbFlowProcessDetail> tbFlowProcessDetailSkip = tbFlowProcessDetailDao.getFlowProcessDetail(paramSkip);
                                if(tbFlowProcessDetailSkip!=null&&tbFlowProcessDetailSkip.size()>0)
                                {
                                    TbFlowProcessDetail tempValue=tbFlowProcessDetailSkip.get(0);

                                    if(tempValue.getIs_skip()!=null&&tempValue.getIs_skip()==0)
                                    {
                                        toLevel=1;
                                    }
                                }
                            }

                            //获取流程明细去,看看有没有下一步流程,没有下一步流程就更新主表到审核完成,如果有就把下一节点,审批人更新到主表上
                            TbFlowProcessDetail param2 = new TbFlowProcessDetail();
                            param2.setFlow_no(_flow_no);
                            param2.setFlow_type(_flow_type);
                            param2.setFlow_level(toLevel);

                            List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
                            if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                                TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                                //更新主表信息
                                TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                                tempFlowProcessMain.setFlow_no(_flow_no);
                                tempFlowProcessMain.setNow_level(tbFlowProcessDetail.getFlow_level());
                                tempFlowProcessMain.setNow_approver(tbFlowProcessDetail.getFlow_approver());
                                if ((_now_level - 1) == 1) {
                                    tempFlowProcessMain.setStatus(1);//草稿箱
                                }
                                //tempFlowProcessMain.setStatus(2);//审核中
                                tempFlowProcessMain.setUpdate_time(new Date());
                                tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                                //更新明细表的信息
                                TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                                tempFlowProcessDetail.setFlow_no(_flow_no);
                                tempFlowProcessDetail.setFlow_level(_now_level);
                                tempFlowProcessDetail.setStatus(1);
                                tempFlowProcessDetail.setUpdate_time(new Date());
                                tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail);

                                TbFlowProcessDetail tempFlowProcessDetail2 = new TbFlowProcessDetail();
                                tempFlowProcessDetail2.setFlow_no(_flow_no);
                                tempFlowProcessDetail2.setFlow_level(toLevel);
                                tempFlowProcessDetail2.setStatus(1);
                                tempFlowProcessDetail2.setUpdate_time(new Date());
                                tempFlowProcessDetail2.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail2);

                                //写入审核记录表
                                TbFlowProcessDetail param3 = new TbFlowProcessDetail();
                                param3.setFlow_no(_flow_no);
                                param3.setFlow_type(_flow_type);
                                param3.setFlow_level(toLevel);
                                List<TbFlowProcessDetail> tbFlowProcessDetailList2 = tbFlowProcessDetailDao.getFlowProcessDetail(param3);
                                TbFlowProcessDetail temp = tbFlowProcessDetailList2.get(0);

                                TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                                tbFlowProcessRecords.setFlow_no(_flow_no);
                                tbFlowProcessRecords.setFlow_type(_flow_type);
                                tbFlowProcessRecords.setFlow_name(temp.getFlow_name());
                                tbFlowProcessRecords.setFlow_level(toLevel);
                                tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                                tbFlowProcessRecords.setResult("节点退回");
                                tbFlowProcessRecords.setRemark(comments);
                                tbFlowProcessRecords.setCreate_time(new Date());
                                tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                                tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                                sendMail(_flow_type, _flow_no, (toLevel - 1));
                            } else {
                                return ResultUtil.error(500, "当前节点已经是第一个节点,无法退回", "", null);
                            }
                        } else {
                            return ResultUtil.error(500, "该流程已审核完成", "", null);
                        }
                    }
                } else {
                    return ResultUtil.error(500, "未查询到该流程", "", null);
                }
                return ResultUtil.success(_flow_no);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getAllTask(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                TbFlowProcessMain param = new TbFlowProcessMain();

                JSONObject jsonObject = JSONObject.parseObject(data);
                String _flow_type = jsonObject.getString("flow_type");
                String _status = jsonObject.getString("status");

                String _flow_no = jsonObject.getString("flow_no");
                String _comp_code = jsonObject.getString("comp_code");
                String now_approver = jsonObject.getString("now_approver");

                //EDA建库 vpl_create_user，工艺设计 designer，PCB封装名称 S1PCBENCPFILENAME，PDM单号 DocumentName，当前处理人now_approver
                String vpl_create_user = jsonObject.getString("vpl_create_user");
                String designer = jsonObject.getString("designer");
                String S1PCBENCPFILENAME = jsonObject.getString("S1PCBENCPFILENAME");
                String DocumentName = jsonObject.getString("DocumentName");

                boolean search1=false;
                boolean search2=false;
                boolean search3=false;
                List<String> flowNoList=new ArrayList<>();

                TbFlowProcessDetail tfpd=new TbFlowProcessDetail();
                tfpd.setVpl_create_user(vpl_create_user);
                tfpd.setDesigner(designer);
                List<TbFlowProcessDetail> tfpdList=new ArrayList<>();
                if((vpl_create_user!=null&&!vpl_create_user.isEmpty())||(designer!=null&&!designer.isEmpty()))
                {
                    tfpdList=tbFlowProcessDetailDao.getFlowProcessDetail(tfpd);
                    search1=true;
                }
                TbFlowCompVplPdm tfcv=new TbFlowCompVplPdm();
                tfcv.setS1PCBENCPFILENAME(S1PCBENCPFILENAME);
                tfcv.setDocumentName(DocumentName);
                List<TbFlowCompVplPdm> tfcvList= new ArrayList<>();
                if((S1PCBENCPFILENAME!=null&&!S1PCBENCPFILENAME.isEmpty())||(DocumentName!=null&&!DocumentName.isEmpty()))
                {
                    tfcvList= tbFlowCompVplPdmDao.getTbFlowCompVplPdm(tfcv);
                    search2=true;
                }

                List<TbTaskVersion> versionList = new ArrayList<>();
                if(_comp_code!=null&&!_comp_code.isEmpty())
                {
                    versionList =tbTaskVersionDao.getTaskVersionByCompCode4(_comp_code,null);
                    search3=true;
                }
                List<Set<String>> listOfFlowNoSetsToCompare = new ArrayList<>();
                if (search1) {
                    Set<String> set1 = tfpdList.stream()
                            .map(TbFlowProcessDetail::getFlow_no) // 请替换为实际获取 flowNo 的方法
                            .collect(Collectors.toSet());
                    listOfFlowNoSetsToCompare.add(set1);
                }

                if (search2) {
                    // 从 tfcvList 中提取所有 flowNo 并转换为 Set
                    Set<String> set2 = tfcvList.stream()
                            .map(TbFlowCompVplPdm::getFlow_no) // 请替换为实际获取 flowNo 的方法
                            .collect(Collectors.toSet());
                    listOfFlowNoSetsToCompare.add(set2);
                }

                if (search3) {
                    // 从 versionList 中提取所有 flowNo 并转换为 Set
                    Set<String> set3 = versionList.stream()
                            .map(TbTaskVersion::getFlow_no) // 请替换为实际获取 flowNo 的方法
                            .collect(Collectors.toSet());
                    listOfFlowNoSetsToCompare.add(set3);
                }
                if (listOfFlowNoSetsToCompare.isEmpty()) {
                    flowNoList = new ArrayList<>();
                }
                else if (listOfFlowNoSetsToCompare.size() == 1) {
                    flowNoList = new ArrayList<>(listOfFlowNoSetsToCompare.get(0));
                }
                else {
                    Set<String> intersectionSet = new HashSet<>(listOfFlowNoSetsToCompare.get(0));
                    for (int i = 1; i < listOfFlowNoSetsToCompare.size(); i++) {
                        intersectionSet.retainAll(listOfFlowNoSetsToCompare.get(i));
                    }
                    flowNoList = new ArrayList<>(intersectionSet);
                }


                Integer page = jsonObject.getInteger("page");
                Integer pageSize = jsonObject.getInteger("pageSize");

                if (page == null || !CommonUtils.isNumeric(page.toString())) {
                    return ResultUtil.error(500, "错误参数page", "Error Param page", null);
                }
                if (pageSize == null || !CommonUtils.isNumeric(pageSize.toString())) {
                    return ResultUtil.error(500, "错误参数pageSize", "Error Param pageSize", null);
                }
                int begin = (page - 1) * pageSize;

                if (_status != null && !_status.isEmpty()) {
                    try {
                        Integer temp = Integer.parseInt(_status);
                        param.setStatus(temp);
                    } catch (NumberFormatException e) {
                        return ResultUtil.error(500, "status 格式错误", "", null);
                    }
                }

                if (_flow_type != null && !_flow_type.isEmpty()) {
                    param.setFlow_type(_flow_type);
                }

                if (_flow_no != null && !_flow_no.isEmpty()) {
                    param.setFlow_no(_flow_no);
                }

                if(now_approver!=null&&!now_approver.isEmpty())
                {
                    param.setNow_approver(now_approver);
                }

                List<TbFlowProcessMain> tbFlowProcessMains = tbFlowProcessMainDao.getFlowProcessMain4(param,flowNoList, begin, pageSize);

                if (tbFlowProcessMains != null && tbFlowProcessMains.size() > 0) {
                    for (TbFlowProcessMain detail : tbFlowProcessMains) {
                        String create = detail.getCreate_user();
                        String nowApprove = detail.getNow_approver();
                        String flowNo = detail.getFlow_no();

                        if (create != null && !create.isEmpty()) {
                            List<String> list = Arrays.asList(create.split(","));

                            detail.setCreate_user_info(user2Dao.getUserInfoByIds(list));
                        }

                        if (nowApprove != null && !nowApprove.isEmpty()) {
                            List<String> list = Arrays.asList(nowApprove.split(","));
                            detail.setNow_approver_info(user2Dao.getUserInfoByIds(list));
                        }
                        
                        TbFlowProcessDetail tfpd1=new TbFlowProcessDetail();
                        tfpd1.setFlow_no(flowNo);

                        List<TbFlowProcessDetail> tfpdList1=tbFlowProcessDetailDao.getFlowProcessDetail(tfpd1);
                        if(tfpdList1!=null&&tfpdList1.size()>0)
                        {
                            TbFlowProcessDetail temp=tfpdList1.get(0);
                            
                            if(temp.getDesigner()!=null&&!temp.getDesigner().isEmpty())
                            {
                                List<String> list = Arrays.asList(temp.getDesigner().split(","));
                                detail.setDesigner_info(user2Dao.getUserInfoByIds(list));
                            }
                            if(temp.getVpl_create_user()!=null&&!temp.getVpl_create_user().isEmpty())
                            {
                                List<String> list = Arrays.asList(temp.getVpl_create_user().split(","));
                                detail.setVpl_create_user_info(user2Dao.getUserInfoByIds(list));
                            }
                        }

                        TbFlowCompVplPdm tfcv1=new TbFlowCompVplPdm();
                        tfcv1.setFlow_no(flowNo);

                        List<TbFlowCompVplPdm> tfcvList1= tbFlowCompVplPdmDao.getTbFlowCompVplPdm2(tfcv1);
                        if(tfcvList1!=null&&tfcvList1.size()>0)
                        {
                            TbFlowCompVplPdm temp=tfcvList1.get(0);

                            detail.setS1PCBENCPFILENAME(temp.getS1PCBENCPFILENAME());
                            detail.setDocumentName(temp.getDocumentName());
                        }

                        if (flowNo != null && !flowNo.isEmpty()) {
                            TbTemplateVersion templateVersion = new TbTemplateVersion();
                            templateVersion.setFlow_no(flowNo);

                            detail.setTemplate_version_info(tbTemplateVersionDao.getTemplateVersionList(templateVersion));

                            List<TbTaskVersion> tbTaskVersionList = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                            if (tbTaskVersionList != null && tbTaskVersionList.size() > 0) {
                                detail.setComp_code(tbTaskVersionList.get(0).getComp_code());
                            }
                        }
                    }

                    if (_comp_code != null && !_comp_code.isEmpty()) {
                        tbFlowProcessMains = tbFlowProcessMains.parallelStream()
                                .filter(item -> _comp_code.equals(item.getComp_code()))
                                .collect(Collectors.toList());
                    }
                }

                List<TbFlowProcessMain> total=tbFlowProcessMainDao.getFlowProcessMain4(param,flowNoList, null, null);

                //return ResultUtil.success(tbFlowProcessMains);
                return ResultUtil.tableSuccess(page, pageSize, total.size(), tbFlowProcessMains);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getMyTask(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                TbFlowProcessMain param = new TbFlowProcessMain();

                JSONObject jsonObject = JSONObject.parseObject(data);
                String _flow_type = jsonObject.getString("flow_type");
                String _status = jsonObject.getString("status");

                String _flow_no = jsonObject.getString("flow_no");
                String _comp_code = jsonObject.getString("comp_code");

                Integer page = jsonObject.getInteger("page");

                Integer pageSize = jsonObject.getInteger("pageSize");

                if (page == null || !CommonUtils.isNumeric(page.toString())) {
                    return ResultUtil.error(500, "错误参数page", "Error Param page", null);
                }
                if (pageSize == null || !CommonUtils.isNumeric(pageSize.toString())) {
                    return ResultUtil.error(500, "错误参数pageSize", "Error Param pageSize", null);
                }
                int begin = (page - 1) * pageSize;

                if (_status != null && !_status.isEmpty()) {
                    try {
                        Integer temp = Integer.parseInt(_status);
                        param.setStatus(temp);
                    } catch (NumberFormatException e) {
                        return ResultUtil.error(500, "status 格式错误", "", null);
                    }
                }

                if (_flow_type != null && !_flow_type.isEmpty()) {
                    param.setFlow_type(_flow_type);
                }

                if (_flow_no != null && !_flow_no.isEmpty()) {
                    param.setFlow_no(_flow_no);
                }

                if (param.getStatus() == 4) {
                    //List<Integer> aaa=UserHeaderHolder.getRoleList();
                    if (!UserHeaderHolder.getRoleList().contains(1) || !UserHeaderHolder.getRoleList().contains(2)) {
                        //非管理员才要加上条件.不然不需要加
                        param.setCreate_user(UserHeaderHolder.getUserId());
                    }
                } else {
                    if (!UserHeaderHolder.getRoleList().contains(1) || !UserHeaderHolder.getRoleList().contains(2)) {
                        //非管理员才要加上条件.不然不需要加
                        param.setNow_approver(UserHeaderHolder.getUserId());
                    }
                }

                List<TbFlowProcessMain> tbFlowProcessMains = tbFlowProcessMainDao.getFlowProcessMain3(param, begin, pageSize);

                if (tbFlowProcessMains != null && tbFlowProcessMains.size() > 0) {
                    for (TbFlowProcessMain detail : tbFlowProcessMains) {
                        String create = detail.getCreate_user();
                        String nowApprove = detail.getNow_approver();
                        String flowNo = detail.getFlow_no();

                        if (create != null && !create.isEmpty()) {
                            List<String> list = Arrays.asList(create.split(","));

                            detail.setCreate_user_info(user2Dao.getUserInfoByIds(list));
                        }

                        if (nowApprove != null && !nowApprove.isEmpty()) {
                            List<String> list = Arrays.asList(nowApprove.split(","));
                            detail.setNow_approver_info(user2Dao.getUserInfoByIds(list));
                        }

                        if (flowNo != null && !flowNo.isEmpty()) {
                            TbTemplateVersion templateVersion = new TbTemplateVersion();
                            templateVersion.setFlow_no(flowNo);

                            detail.setTemplate_version_info(tbTemplateVersionDao.getTemplateVersionList(templateVersion));

                            List<TbTaskVersion> tbTaskVersionList = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                            if (tbTaskVersionList != null && tbTaskVersionList.size() > 0) {
                                detail.setComp_code(tbTaskVersionList.get(0).getComp_code());
                            }
                        }
                    }

                    if (_comp_code != null && !_comp_code.isEmpty()) {
                        tbFlowProcessMains = tbFlowProcessMains.parallelStream()
                                .filter(item -> _comp_code.equals(item.getComp_code()))
                                .collect(Collectors.toList());
                    }
                }

                //return ResultUtil.success(tbFlowProcessMains);
                return ResultUtil.tableSuccess(page, pageSize, tbFlowProcessMainDao.getFlowProcessMain3(param, null, null).size(), tbFlowProcessMains);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result deleteTaskData(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _flow_type = jsonObject.getString("flow_type");
                String _flow_no = jsonObject.getString("flow_no");
                String _flow_level = jsonObject.getString("flow_level");
                String _parent_param_key = jsonObject.getString("parent_param_key");
                Integer _row_sort = jsonObject.getInteger("row_sort");

                //限制模板类型
                if (!_flow_type.equals("device") && !_flow_type.equals("design") && !_flow_type.equals("vpl")) {
                    return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                }

                //_parent_param_key 不允许为空
                if (_parent_param_key == null || _parent_param_key.isEmpty()) {
                    return ResultUtil.error(500, "parent_param_key 参数不正确", "", null);
                }
                //删除的话永远保留第一行,如果不是第一行的话才删除
                if (_row_sort == null) {
                    return ResultUtil.error(500, "row_sort 参数不正确", "", null);
                }
                //删除操作

                if (_parent_param_key.equals("description") || _parent_param_key.equals("application")) {
                    TbTaskTemplateData tbTaskTemplateData = new TbTaskTemplateData();
                    tbTaskTemplateData.setFlow_no(_flow_no);
                    tbTaskTemplateData.setRow_sort(_row_sort);
                    tbTaskTemplateData.setParent_param_key("description");
                    tbTaskTemplateDataDao.deleteTaskTemplateData(tbTaskTemplateData);

                    TbTaskTemplateData tbTaskTemplateData1 = new TbTaskTemplateData();
                    tbTaskTemplateData1.setFlow_no(_flow_no);
                    tbTaskTemplateData1.setRow_sort(_row_sort);
                    tbTaskTemplateData1.setParent_param_key("application");
                    tbTaskTemplateDataDao.deleteTaskTemplateData(tbTaskTemplateData1);
                } else {
                    TbTaskTemplateData tbTaskTemplateData = new TbTaskTemplateData();
                    tbTaskTemplateData.setFlow_no(_flow_no);
                    tbTaskTemplateData.setRow_sort(_row_sort);
                    tbTaskTemplateData.setParent_param_key(_parent_param_key);
                    tbTaskTemplateDataDao.deleteTaskTemplateData(tbTaskTemplateData);
                }

                return ResultUtil.success(_flow_no);

                /**
                 if (_flow_type.equals("design")) {
                 //_parent_param_key 不允许为空
                 if (_parent_param_key == null || _parent_param_key.isEmpty()) {
                 return ResultUtil.error(500, "parent_param_key 参数不正确", "", null);
                 }
                 //删除的话永远保留第一行,如果不是第一行的话才删除
                 if (_row_sort == null) {
                 return ResultUtil.error(500, "row_sort 参数不正确", "", null);
                 }
                 //删除操作
                 TbTaskTemplateData tbTaskTemplateData = new TbTaskTemplateData();
                 tbTaskTemplateData.setFlow_no(_flow_no);
                 tbTaskTemplateData.setRow_sort(_row_sort);
                 tbTaskTemplateData.setParent_param_key(_parent_param_key);

                 tbTaskTemplateDataDao.deleteTaskTemplateData(tbTaskTemplateData);

                 return ResultUtil.success(_flow_no);
                 } else if (_flow_type.equals("device")) {
                 return ResultUtil.success("功能未完成");
                 } else if (_flow_type.equals("vpl")) {
                 return ResultUtil.success("功能未完成");
                 } else {
                 return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                 }*/
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    @Override
    public Result deleteTask(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                Integer _id = jsonObject.getInteger("id");

                //先去查询一下流程信息
                //然后作区分
                List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMainById(_id);

                if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                    TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);
                    String _flow_type = tbFlowProcessMain.getFlow_type();
                    String _flow_no = tbFlowProcessMain.getFlow_no();

                    Integer _status = tbFlowProcessMain.getStatus();

                    if (_status == 3 && !(UserHeaderHolder.getRoleList().contains(1) || UserHeaderHolder.getRoleList().contains(2))) {
                        return ResultUtil.error(500, "任务已归档，只有管理员可以删除", "", null);
                    }
                    if (_status == 3 && !_flow_type.equals("vpl")) {
                        return ResultUtil.error(500, "任务已归档，只可以删除VPL流程", "", null);
                    }
                    //List<Integer> aaa=UserHeaderHolder.getRoleList();
                    if (_status == 2 && !(UserHeaderHolder.getRoleList().contains(1) || UserHeaderHolder.getRoleList().contains(2))) {
                        return ResultUtil.error(500, "任务进行中，只有管理员可以删除", "", null);
                    }
                    tbFlowProcessMainDao.deleteFlowProcessMainById(_id);
                    tbFlowProcessDetailDao.deleteTbFlowProcessDetailByFlowNo(_flow_no);
                    tbTaskVersionDao.deleteTaskVersionByFlowNo(_flow_no);
                    tbFlowProcessRecordsDao.deleteFlowProcessRecordsByFlowNo(_flow_no);
                    tbKnowledgeBaseFileDao.deleteTbKnowledgeBaseFileByFlowNo(_flow_no);

                    if (_flow_type.equals("design")) {
                        //删除流程信息
                        tbTaskTemplateDataDao.deleteTaskTemplateDataByFlowNo(_flow_no);

                        return ResultUtil.success("操作成功");
                    } else if (_flow_type.equals("device")) {

                        tbFlowCompVplDao.deleteTbFlowCompVplByFlowNo(_flow_no);
                        tbFlowCompPkgDao.deleteTbFlowCompPkgByFlowNo(_flow_no);
                        tbFlowCompManufacturerDao.deleteTbFlowCompManufacturerByFlowNo(_flow_no);
                        tbFlowCompVplAttrDao.deleteTbFlowCompVplAttrByFlowNo(_flow_no);
                        tbFlowCompVplPinAttrDao.deleteTbFlowCompVplPinAttrByFlowNo(_flow_no);
                        tbTaskTemplateDataDao.deleteTaskTemplateDataByFlowNo(_flow_no);

                        return ResultUtil.success("操作成功");
                    } else if (_flow_type.equals("vpl")) {
                        tbFlowCompVplPdmDao.deleteTbTbFlowCompVplPdmByFlowNo(_flow_no);
                        tbFlowCompManufacturerDao.deleteTbFlowCompManufacturerByFlowNo(_flow_no);
                        tbFlowCompVplAttrDao.deleteTbFlowCompVplAttrByFlowNo(_flow_no);
                        tbFlowCompVplPinAttrDao.deleteTbFlowCompVplPinAttrByFlowNo(_flow_no);
                        tbFlowCompPkgDao.deleteTbFlowCompPkgByFlowNo(_flow_no);
                        tbFlowCompVplDao.deleteTbFlowCompVplByFlowNo(_flow_no);
                        tbTaskTemplateDataDao.deleteTaskTemplateDataByFlowNo(_flow_no);

                        return ResultUtil.success("操作成功");
                    } else {
                        return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                    }

                } else {
                    return ResultUtil.error(500, "未查询到该流程数据", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    @Override
    public Result deleteCompManufacturer(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                Integer _id = jsonObject.getInteger("id");

                Integer result = tbFlowCompManufacturerDao.deleteTbFlowCompManufacturerById(_id);
                if (result > 0) {
                    return ResultUtil.success("删除成功");
                } else {
                    return ResultUtil.error(500, "删除失败,数据不存在或者数据来源于PDM,不允许删除", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    @Override
    public Result cancelTask(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                //Integer _id = jsonObject.getInteger("id");
                String _flow_no = jsonObject.getString("flow_no");

                //先去查询一下流程信息
                //然后作区分
                List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);

                if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                    TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);
                    Integer _now_level = tbFlowProcessMain.getNow_level();
                    //String _flow_no = tbFlowProcessMain.getFlow_no();
                    if (_now_level == 1) {
                        //撤销流程,修改两个表
                        tbTaskVersionDao.cancelTaskVersion(_flow_no);
                        tbFlowProcessMainDao.cancelFlowProcessMain(_flow_no);

                        return ResultUtil.success("撤销成功");
                    } else {
                        return ResultUtil.error(500, "当前流程不在第一个节点,无法撤销", "", null);
                    }
                } else {
                    return ResultUtil.error(500, "未查询到该流程数据", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result authorizeApprover(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _flow_no = jsonObject.getString("flow_no");
                Integer _flow_level = jsonObject.getInteger("flow_level");
                String _approver = jsonObject.getString("approver");

                //判断是否为空
                if (_flow_no == null || _flow_no.isEmpty()) {
                    return ResultUtil.error(500, "flow_no不可以为空", "", null);
                }

                if (_flow_level == null) {
                    return ResultUtil.error(500, "flow_level不可以为空", "", null);
                }

                if (_approver == null || _approver.isEmpty()) {
                    return ResultUtil.error(500, "approver不可以为空", "", null);
                }

                //查询当前节点是否已经被审批结束了,如果审批结束了就不允许再修改当前的审批人信息
                TbFlowProcessDetail param = new TbFlowProcessDetail();
                param.setFlow_no(_flow_no);
                param.setFlow_approver(_approver);
                param.setFlow_level(_flow_level);

                //判断当前是否已经审批完成了
                List<TbFlowProcessDetail> list = tbFlowProcessDetailDao.getFlowProcessDetail(param);

                if (list == null || list.size() == 0) {
                    return ResultUtil.error(500, "未查询到该流程数据", "", null);
                } else {
                    TbFlowProcessDetail tbFlowProcessDetail = list.get(0);
                    if (tbFlowProcessDetail.getStatus() == 2) {
                        return ResultUtil.error(500, "该节点已审核完成", "", null);
                    }
                }

                param.setUpdate_time(new Date());
                param.setUpdate_user(UserHeaderHolder.getUserId());

                //修改当前节点审批人
                tbFlowProcessDetailDao.updateFlowProcessDetailApprover(param);

                //修改流程主信息

                //TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                //tbFlowProcessMain.setNow_level(_flow_level);
                //tbFlowProcessMain.setNow_approver(_approver);
                //tbFlowProcessMain.setFlow_no(_flow_no);
                //tbFlowProcessMain.setUpdate_time(new Date());
                //tbFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());

                //获取流程主信息
                List<TbFlowProcessMain> tbFlowProcessMainList = new ArrayList<>();
                tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);
                if (tbFlowProcessMainList == null || tbFlowProcessMainList.size() == 0) {
                    return ResultUtil.error(500, "未查询到该流程数据", "", null);
                }
                TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);
                if (tbFlowProcessMain.getStatus() != null && tbFlowProcessMain.getStatus() == 4) {
                    tbFlowProcessMainDao.updateFlowProcessMainForAuthorize2(_approver, _flow_no, _flow_level, 2);
                } else {
                    tbFlowProcessMainDao.updateFlowProcessMainForAuthorize(_approver, _flow_no, _flow_level);
                }

                return ResultUtil.success(_flow_no);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getPartInfoFromPDM(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _comp_code = jsonObject.getString("comp_code");

                if (_comp_code == null || _comp_code.isEmpty()) {
                    return ResultUtil.error(500, "comp_code参数为空", "", null);
                }

                PdmNewPartApplication param = new PdmNewPartApplication();
                param.setS1partnumber(_comp_code);
                //先去查询pdm的库,然后再查询已经存在的库,然后剔除掉已经存在的数据
                List<PdmNewPartApplication> listPdmNewPartApplication = pdmNewPartApplicationDao.getPdmNewPartApplicationList(param);

                if (listPdmNewPartApplication == null || listPdmNewPartApplication.size() <= 0) {
                    return ResultUtil.error(500, "未在PDM中查询到该器件编码有效信息,请确认!", "", null);
                }

                //再查询出来当前数据库已经有的料号的流程
                List<TbTaskVersion> listTbTaskVersion = tbTaskVersionDao.getTaskVersionByCompCode(_comp_code);

                if (listTbTaskVersion != null && listTbTaskVersion.size() > 0) {
                    return ResultUtil.error(500, "该器件编码已创建流程,请勿重复创建,流程编号为:" + listTbTaskVersion.get(0).getFlow_no() + "", "", null);
                }

                // 创建一个新的列表，用于存储剔除后的数据
                List<PdmNewPartApplication> newListPdmNewPartApplication = new ArrayList<>();

                // 遍历listPdmNewPartApplication，检查comp_code是否在listTbTaskVersion中存在
                for (PdmNewPartApplication pdmNewPartApplication : listPdmNewPartApplication) {
                    String compCode = pdmNewPartApplication.getS1partnumber();
                    boolean exists = listTbTaskVersion.stream()
                            .filter(Objects::nonNull) // 过滤掉null值
                            .filter(version -> version.getComp_code() != null) // 过滤掉comp_code为空的元素
                            .anyMatch(version -> version.getComp_code().equals(compCode));
                    if (!exists) {
                        newListPdmNewPartApplication.add(pdmNewPartApplication);
                    }
                }
                //拿到新的list以后,按照文档编号进行分组,查询出来有多少个编号信息
                Set<String> uniqueS1partnumbers = newListPdmNewPartApplication.stream()
                        .map(PdmNewPartApplication::getS1partnumber)
                        .collect(Collectors.toSet());

                List<Map<String, Object>> finalList = new ArrayList<>();
                for (String partNumber : uniqueS1partnumbers) {
                    Map<String, Object> tempMap = new HashMap<>();

                    List<PdmNewPartApplication> extractedFieldsList = newListPdmNewPartApplication.stream()
                            .filter(p -> partNumber.equals(p.getS1partnumber())) // 替换 "s1part" 为你的查询条件
                            .collect(Collectors.toList()); // 收集结果到一个新的列表

                    List<TbFlowCompVplPdm> listTbFlowCompVplPdm = new ArrayList<>();

                    if (!extractedFieldsList.isEmpty()) {
                        PdmNewPartApplication firstItem = extractedFieldsList.get(0);
                        TbFlowCompVplPdm convertedItem = new TbFlowCompVplPdm();

                        convertedItem.setDocumentName(firstItem.getDocumentName());
                        convertedItem.setS1PCBENCPFILENAME(firstItem.getS1PCBENCPFILENAME());
                        convertedItem.setS1partnumber(firstItem.getS1partnumber());
                        convertedItem.setS1partdescelements(firstItem.getS1partdescelements());
                        convertedItem.setH3productline(firstItem.getH3productline());
                        convertedItem.setH3product(firstItem.getH3product());
                        //处理一下人员信息,因为是字符串分隔的,所以需要拆分
                        //建库人员
                        if (firstItem.getEDA_JKR_Last_SPR() != null && !firstItem.getEDA_JKR_Last_SPR().isEmpty()) {
                            String[] split = firstItem.getEDA_JKR_Last_SPR().split(" ");
                            if (split != null && split.length > 0) {
                                if (split[1] != null && !split[1].isEmpty()) {
                                    List<String> List = Arrays.asList(split[1].split(","));

                                    List<User2> user2List = user2Dao.getUserInfoByCode(List);
                                    if (user2List != null && user2List.size() > 0) {
                                        convertedItem.setVpl_create_user(user2List.get(0).getUser_id());
                                        convertedItem.setVpl_create_user_info(user2List);
                                    }
                                }
                            }
                        }

                        //工艺审核人员
                        if (firstItem.getGYSH_Last_SPR() != null && !firstItem.getGYSH_Last_SPR().isEmpty()) {
                            String[] split1 = firstItem.getGYSH_Last_SPR().split(" ");
                            if (split1 != null && split1.length > 0) {

                                if (split1[1] != null && !split1[1].isEmpty()) {
                                    List<String> List = Arrays.asList(split1[1].split(","));

                                    List<User2> user2List = user2Dao.getUserInfoByCode(List);
                                    if (user2List != null && user2List.size() > 0) {
                                        convertedItem.setDesigner(user2List.get(0).getUser_id());
                                        convertedItem.setDesigner_info(user2List);
                                    }
                                }
                            }
                        }
                        listTbFlowCompVplPdm.add(convertedItem);
                    }
                    tempMap.put("compVplPdm", listTbFlowCompVplPdm);
                    if (listTbFlowCompVplPdm != null && listTbFlowCompVplPdm.size() > 0) {
                        tempMap.put("vpl_create_user", listTbFlowCompVplPdm.get(0).getVpl_create_user());
                        tempMap.put("vpl_create_user_info", listTbFlowCompVplPdm.get(0).getVpl_create_user_info());

                        tempMap.put("designer", listTbFlowCompVplPdm.get(0).getDesigner());
                        tempMap.put("designer_info", listTbFlowCompVplPdm.get(0).getDesigner_info());
                    }

                    List<TbFlowCompManufacturer> convertedList = extractedFieldsList.stream()
                            .map(item -> {
                                TbFlowCompManufacturer convertedItem = new TbFlowCompManufacturer();
                                convertedItem.setManufacturer(item.getManufacturer());
                                convertedItem.setManufacturer_type(item.getS1MANUPARTNUM());
                                convertedItem.setData_sources("PDM");
                                return convertedItem;
                            })
                            .collect(Collectors.toList());
                    tempMap.put("compManufacturer", convertedList);

                    //20250311添加数据来源字段
                    //tempMap.put("data_sources","PDM");

                    finalList.add(tempMap);
                }

                if (finalList == null || finalList.size() == 0) {
                    return ResultUtil.error(500, "未查询到编码信息", "", null);
                } else {
                    return ResultUtil.success(finalList);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getPartInfoFormFlow(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _comp_code = jsonObject.getString("comp_code");

                if (_comp_code == null || _comp_code.isEmpty()) {
                    return ResultUtil.error(500, "comp_code不可以为空", "", null);
                }

                //那要先查询是否有正在审核的流程
                List<TbTaskVersion> taskVersionList = tbTaskVersionDao.getTaskVersionByCompCode2(_comp_code, "device", 3);
                if (taskVersionList != null && taskVersionList.size() > 0) {
                    return ResultUtil.error(500, "当前料号已经创建了该流程", "", null);
                }

                //没有正在审核的流程,那就去数据库查当前最新版本的device信息
                //如果没查到的话,那就是要查vpl流程了.
                List<TbTaskVersion> taskVersionList2 = tbTaskVersionDao.getTaskVersionByCompCode3(_comp_code, "device", 3);

                List<Map<String, Object>> list = new ArrayList<>();
                if (taskVersionList2 != null && taskVersionList2.size() > 0) {
                    Map<String, Object> combinedMap = new HashMap<>();
                    //查到了以后就去获取对象信息
                    TbTaskVersion tbTaskVersion = taskVersionList2.get(0);

                    combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(tbTaskVersion.getFlow_no(), 1));
                    combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(tbTaskVersion.getFlow_no(), 1));
                    combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(tbTaskVersion.getFlow_no(), 1));
                    combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(tbTaskVersion.getFlow_no(), 1));
                    combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(tbTaskVersion.getFlow_no(), 1));

                    list.add(combinedMap);
                } else {
                    //没查到,那就是查vpl流程了
                    List<TbTaskVersion> taskVersionList3 = tbTaskVersionDao.getTaskVersionByCompCode3(_comp_code, "vpl", 3);
                    if (taskVersionList3 != null && taskVersionList3.size() > 0) {
                        Map<String, Object> combinedMap = new HashMap<>();
                        TbTaskVersion tbTaskVersion = taskVersionList3.get(0);

                        combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(tbTaskVersion.getFlow_no(), 4));
                        combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(tbTaskVersion.getFlow_no(), 3));
                        combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(tbTaskVersion.getFlow_no(), 1));
                        combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(tbTaskVersion.getFlow_no(), 2));
                        combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(tbTaskVersion.getFlow_no(), 2));
                        list.add(combinedMap);
                    }
                }

                if (list == null || list.size() <= 0) {
                    //没有查到,那就是没有创建过流程
                    return ResultUtil.error(500, "该料号需要走新建VPL流程", "", null);
                }

                return ResultUtil.success(list.get(0));
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    public Result handleAdd(String _flow_type, JSONObject jsonObject, String tempTemplateName, Integer status, String type) {
        String _flow_no = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());
        TbFlowProcessMain byFlowNo = tbFlowProcessMainDao.getByFlowNo(currentDate);
        int currentSeq = 0;
        if (byFlowNo != null) {
            currentSeq = byFlowNo.getSeq();
        }
        currentSeq++;
        //流程编号
        _flow_no = currentDate + String.format("%05d", currentSeq);
        String version = UUID.randomUUID().toString();
        //获取审核流程
        List<TbFlowDetail> listFlow = tbFlowDetailDao.getFolwListByType(_flow_type);
        //写入审核流程信息
        List<TbFlowProcessDetail> listFlowTemplate = new ArrayList<>();
        for (TbFlowDetail flow : listFlow) {
            listFlowTemplate.add(new TbFlowProcessDetail(
                    _flow_no,
                    flow.flow_type,
                    flow.flow_name,
                    flow.flow_level,
                    flow.flow_approver,
                    1,
                    flow.sort,
                    UserHeaderHolder.getUserId(),
                    new Date()));
        }
        if (_flow_type.equals("vpl")) {
            for (TbFlowProcessDetail detail : listFlowTemplate) {
                detail.setIs_need_knowledge_base(1);
            }
        }

        String _tempCreater = "";

        if (!type.equals("auto")) {
            _tempCreater = UserHeaderHolder.getUserId();
        }


        //获取当前流程的第一个对象
        TbFlowProcessDetail firstFlowProcessDetail = listFlowTemplate.get(0);

        //获取前端传过来的信息授权信息
        if (jsonObject.containsKey("flowInfo")) {
            String comments = jsonObject.getJSONObject("flowInfo").getString("comments");
            String flowApprover = jsonObject.getJSONObject("flowInfo").getString("flow_approver");
            String designer = jsonObject.getJSONObject("flowInfo").getString("designer");
            String vplCreateUser = jsonObject.getJSONObject("flowInfo").getString("vpl_create_user");

            firstFlowProcessDetail.setComments(comments);
            //20250318 修改流程第一节点的处理人,谁创建的就归谁
            if (type.equals("auto")) {
                firstFlowProcessDetail.setFlow_approver(flowApprover);
            } else {
                firstFlowProcessDetail.setFlow_approver(UserHeaderHolder.getUserId());
            }

            firstFlowProcessDetail.setDesigner(designer);
            firstFlowProcessDetail.setVpl_create_user(vplCreateUser);

            if (_tempCreater == null || _tempCreater.isEmpty()) {
                _tempCreater = vplCreateUser;
            }

            if (_flow_type.equals("vpl")) {
                //20250918 新增字段是否需要VPL建库  1是需要 0是不需要,默认就是1
                Integer is_skip=jsonObject.getInteger("is_skip");
                if(is_skip!=null)
                {
                    firstFlowProcessDetail.setIs_skip(is_skip);
                }
                else
                {
                    firstFlowProcessDetail.setIs_skip(1);
                }

                String other_resource = jsonObject.getJSONObject("flowInfo").getString("other_resource");
                String cc = jsonObject.getJSONObject("flowInfo").getString("cc");
                //String difficulty = jsonObject.getJSONObject("flowInfo").getString("difficulty");
                //String equivalent_num = jsonObject.getJSONObject("flowInfo").getString("equivalent_num");

                firstFlowProcessDetail.setOther_resource(other_resource);
                firstFlowProcessDetail.setCc(cc);
                //firstFlowProcessDetail.setDifficulty(difficulty);
                //firstFlowProcessDetail.setEquivalent_num(equivalent_num);

                if (vplCreateUser == null || vplCreateUser.isEmpty()) {
                    //throw new Exception("建库人员不能为空");
                    return ResultUtil.error(500, "建库人员不能为空", "", null);
                }

                if (designer == null || designer.isEmpty()) {
                    //throw new Exception("工艺设计人员不能为空");
                    return ResultUtil.error(500, "工艺设计人员不能为空", "", null);
                }


                Object other_resource_filesType = jsonObject.getJSONObject("flowInfo").get("other_resource_files");
                if (other_resource_filesType instanceof JSONArray) {
                    JSONArray other_resource_filesArray = jsonObject.getJSONObject("flowInfo").getJSONArray("other_resource_files") == null ? null : jsonObject.getJSONObject("flowInfo").getJSONArray("other_resource_files");
                    if (other_resource_filesArray != null) {
                        List<String> keyList = new ArrayList<>();

                        for (int i = 0; i < other_resource_filesArray.size(); i++) {

                            JSONObject other_resource_files = other_resource_filesArray.getJSONObject(i);

                            String _param_key = String.valueOf(UUID.randomUUID());
                            keyList.add(_param_key);
                            //updateParam.setOther_resource_files(_param_key);
                            //updateParam.setVpl_model_excel(_param_key);
                            TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                            tbKnowledgeBaseFile.setFlow_no(_flow_no);
                            tbKnowledgeBaseFile.setFlow_level(1);
                            tbKnowledgeBaseFile.setParam_key(_param_key);

                            String filename = other_resource_files.get("file_name") == null ? null : other_resource_files.get("file_name").toString();
                            tbKnowledgeBaseFile.setFile_name(filename);
                            tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                            tbKnowledgeBaseFile.setFile_relate_path(other_resource_files.get("picRelatePath") == null ? null : other_resource_files.get("picRelatePath").toString());
                            tbKnowledgeBaseFile.setFile_type(3);
                            tbKnowledgeBaseFile.setSecret_key(other_resource_files.get("secretKey") == null ? null : other_resource_files.get("secretKey").toString());
                            tbKnowledgeBaseFile.setFile_sid(other_resource_files.get("fileSid") == null ? null : other_resource_files.get("fileSid").toString());

                            List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                            tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                            tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                        }

                        if (keyList != null && keyList.size() > 0) {
                            firstFlowProcessDetail.setOther_resource_files(String.join(",", keyList));
                        }
                    }
                }
            }

        }
        listFlowTemplate.set(0, firstFlowProcessDetail);

        //if (_flow_type.equals("vpl") && jsonObject.containsKey("flowInfo")) {
        //    TbFlowProcessDetail secondFlowProcessDetail = listFlowTemplate.get(1);
        //    secondFlowProcessDetail.setFlow_approver(jsonObject.getJSONObject("flowInfo").getString("flow_approver"));
        //    listFlowTemplate.set(1, secondFlowProcessDetail);
        //}
        //TbFlowDetail firstFlow = listFlow.get(0);
        //写入主表信息
        TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
        tbFlowProcessMain.setFlow_no(_flow_no);
        tbFlowProcessMain.setFlow_type(_flow_type);
        tbFlowProcessMain.setSeq(currentSeq);
        tbFlowProcessMain.setNow_level(firstFlowProcessDetail.getFlow_level());
        tbFlowProcessMain.setNow_approver(firstFlowProcessDetail.getFlow_approver());
        if (status == null) {
            tbFlowProcessMain.setStatus(4);
        } else {
            tbFlowProcessMain.setStatus(status);
        }

        tbFlowProcessMain.setCreate_time(new Date());
        tbFlowProcessMain.setCreate_user(_tempCreater);

        //20250320 新增判断逻辑,除了VPL的,剩下的device和design都走这个逻辑,vpl的是在固定的第四个节点去更新数据
        //考虑先把这个判断去掉,以后跟新以后还是可以替换这个id值的
        //if(!_flow_type.equals("vpl"))
        //{
        String knowledge_base_key = jsonObject.getString("knowledge_base_key");
        if (knowledge_base_key != null && !knowledge_base_key.isEmpty()) {
            tbFlowProcessMain.setKnowledge_base_key(knowledge_base_key);
        } else {
            tbFlowProcessMain.setKnowledge_base_key(String.valueOf(UUID.randomUUID()));
        }
        //}

        Integer _sort = 1;
        List<TbTaskVersion> listTaskVersion = tbTaskVersionDao.getNewestTaskVersion(_flow_type);
        if (listTaskVersion != null && listTaskVersion.size() > 0) {
            TbTaskVersion tbTaskVersion = listTaskVersion.get(0);
            _sort = tbTaskVersion.getSort() + 1;
        }
        TbTaskVersion tbTaskVersion = new TbTaskVersion();
        tbTaskVersion.setVersion(version);
        tbTaskVersion.setTask_type(_flow_type);
        tbTaskVersion.setCreate_user(_tempCreater);
        tbTaskVersion.setCreate_time(new Date());
        tbTaskVersion.setSort(_sort);
        tbTaskVersion.setFlow_no(_flow_no);
        tbTaskVersion.setStatus(1);

        if (_flow_type.equals("design") || _flow_type.equals("device")) {

            if (_flow_type.equals("device")) {
                //写表
                //compVpl
                //compPkg
                //compManufacturer
                //compVplAttr
                //compVplPinAttr
                String tempComp = "";
                JSONArray compVpls = jsonObject.getJSONArray("compVpl");
                if (compVpls != null) {
                    List<TbFlowCompVpl> listTbFlowCompVpl = new ArrayList<>();

                    for (int i = 0; i < compVpls.size(); i++) {
                        JSONObject compVpl = compVpls.getJSONObject(i);

                        TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                        tbFlowCompVpl.setFlow_no(_flow_no);
                        tbFlowCompVpl.setFlow_level(1);
                        tbFlowCompVpl.setCreate_time(new Date());
                        tbFlowCompVpl.setCreate_user(_tempCreater);
                        tbFlowCompVpl.setComp_code(compVpl.getString("comp_code"));
                        tempComp = compVpl.getString("comp_code");

                        //if(tempComp==null||tempComp.isEmpty())
                        //{
                        //    return ResultUtil.error(500, "comp_code 不可以为空", "", null);
                        //}

                        tbFlowCompVpl.setComp_type(compVpl.getString("comp_type"));
                        tbFlowCompVpl.setPkg_name(compVpl.getString("pkg_name"));
                        tbFlowCompVpl.setAssembly_type(compVpl.getString("assembly_type"));
                        tbFlowCompVpl.setComponent_high_max_vpl(compVpl.getString("component_high_max_vpl"));
                        tbFlowCompVpl.setComponent_high_max_pdm(compVpl.getString("component_high_max_pdm"));
                        tbFlowCompVpl.setIs_dense_comp(compVpl.getString("is_dense_comp"));
                        tbFlowCompVpl.setStress_properties(compVpl.getString("stress_properties"));
                        tbFlowCompVpl.setPin_high_max(compVpl.getString("pin_high_max"));
                        tbFlowCompVpl.setPin_high_min(compVpl.getString("pin_high_min"));
                        tbFlowCompVpl.setPastemask_thickness_max(compVpl.getString("pastemask_thickness_max"));
                        tbFlowCompVpl.setPastemask_thickness_min(compVpl.getString("pastemask_thickness_min"));
                        tbFlowCompVpl.setPth_diameter_min(compVpl.getString("pth_diameter_min"));
                        tbFlowCompVpl.setPin_min_pitch(compVpl.getString("pin_min_pitch"));
                        tbFlowCompVpl.setIs_tht_power(compVpl.getString("is_tht_power"));
                        tbFlowCompVpl.setIs_tht_capcitor(compVpl.getString("is_tht_capcitor"));
                        tbFlowCompVpl.setIs_glue(compVpl.getString("is_glue"));
                        tbFlowCompVpl.setIs_little_retentionforce(compVpl.getString("is_little_retentionforce"));

                        listTbFlowCompVpl.add(tbFlowCompVpl);
                    }

                    if (listTbFlowCompVpl.size() > 0) {
                        tbFlowCompVplDao.insertTbFlowCompVplBatch(listTbFlowCompVpl);
                    }
                }

                JSONArray compPkgs = jsonObject.getJSONArray("compPkg");
                if (compPkgs != null) {
                    List<TbFlowCompPkg> listTbFlowCompPkg = new ArrayList<>();

                    for (int i = 0; i < compPkgs.size(); i++) {
                        JSONObject compPkg = compPkgs.getJSONObject(i);

                        TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                        tbFlowCompPkg.setFlow_no(_flow_no);
                        tbFlowCompPkg.setFlow_level(1);
                        tbFlowCompPkg.setCreate_time(new Date());
                        tbFlowCompPkg.setCreate_user(_tempCreater);
                        tbFlowCompPkg.setPkg_name(compPkg.getString("pkg_name"));
                        tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                        tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                        tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                        tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                        tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                        tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                        tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                        tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                        tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                        tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                        tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                        tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                        tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                        tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));

                        listTbFlowCompPkg.add(tbFlowCompPkg);
                    }

                    if (listTbFlowCompPkg.size() > 0) {
                        tbFlowCompPkgDao.insertTbFlowCompPkgBatch(listTbFlowCompPkg);
                    }
                }

                JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");
                if (compManufacturers != null) {
                    List<TbFlowCompManufacturer> listTbFlowCompManufacturer = new ArrayList<>();
                    for (int i = 0; i < compManufacturers.size(); i++) {
                        JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                        TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                        tbFlowCompManufacturer.setFlow_no(_flow_no);
                        tbFlowCompManufacturer.setFlow_level(1);
                        tbFlowCompManufacturer.setCreate_time(new Date());
                        tbFlowCompManufacturer.setCreate_user(_tempCreater);
                        tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                        tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));
                        tbFlowCompManufacturer.setWeight(compManufacturer.getString("weight"));
                        tbFlowCompManufacturer.setCoplanarity(compManufacturer.getString("coplanarity"));
                        tbFlowCompManufacturer.setStandoff(compManufacturer.getString("standoff"));
                        tbFlowCompManufacturer.setSolder_tg_max(compManufacturer.getString("solder_tg_max"));
                        tbFlowCompManufacturer.setBga_height_min(compManufacturer.getString("bga_height_min"));
                        tbFlowCompManufacturer.setUnbd_thickness_min(compManufacturer.getString("unbd_thickness_min"));
                        tbFlowCompManufacturer.setBoard_thickness_min(compManufacturer.getString("board_thickness_min"));
                        tbFlowCompManufacturer.setBoard_thickness_max(compManufacturer.getString("board_thickness_max"));
                        tbFlowCompManufacturer.setIs_secd_reflow_drop(compManufacturer.getString("is_secd_reflow_drop"));
                        tbFlowCompManufacturer.setThermal_contact_dimension(compManufacturer.getString("thermal_contact_dimension"));

                        listTbFlowCompManufacturer.add(tbFlowCompManufacturer);
                    }
                    if (listTbFlowCompManufacturer.size() > 0) {
                        tbFlowCompManufacturerDao.insertTbFlowCompManufacturerBatch(listTbFlowCompManufacturer);
                    }
                }

                JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");
                if (compVplAttrs != null) {
                    List<TbFlowCompVplAttr> listTbFlowCompVplAttr = new ArrayList<>();
                    for (int i = 0; i < compVplAttrs.size(); i++) {
                        JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                        TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();
                        tbFlowCompVplAttr.setFlow_no(_flow_no);
                        tbFlowCompVplAttr.setFlow_level(1);
                        tbFlowCompVplAttr.setCreate_time(new Date());
                        tbFlowCompVplAttr.setCreate_user(_tempCreater);
                        tbFlowCompVplAttr.setManufacturer_type(compVplAttr.getString("manufacturer_type"));
                        tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                        tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                        tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));
                        tbFlowCompVplAttr.setCoplanarity(compVplAttr.getString("coplanarity"));
                        tbFlowCompVplAttr.setWeight(compVplAttr.getString("weight"));
                        tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                        tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                        tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                        tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                        tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                        tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                        tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                        tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                        tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                        tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));
                        tbFlowCompVplAttr.setStandoff(compVplAttr.getString("standoff"));
                        tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                        tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                        tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                        tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                        tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                        tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                        tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                        listTbFlowCompVplAttr.add(tbFlowCompVplAttr);
                    }
                    if (listTbFlowCompVplAttr.size() > 0) {
                        tbFlowCompVplAttrDao.insertTbFlowCompVplAttrBatch(listTbFlowCompVplAttr);
                    }
                }

                JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                if (compVplPinAttrs != null) {
                    List<TbFlowCompVplPinAttr> listTbFlowCompVplPinAttr = new ArrayList<>();
                    for (int i = 0; i < compVplPinAttrs.size(); i++) {
                        JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);
                        TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();
                        tbFlowCompVplPinAttr.setFlow_no(_flow_no);
                        tbFlowCompVplPinAttr.setFlow_level(1);
                        tbFlowCompVplPinAttr.setCreate_time(new Date());
                        tbFlowCompVplPinAttr.setCreate_user(_tempCreater);

                        tbFlowCompVplPinAttr.setMpn(compVplPinAttr.getString("mpn"));
                        tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                        tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                        tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                        tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                        tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                        tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                        tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                        tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                        tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                        tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                        tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                        tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                        tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                        tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                        tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                        tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                        listTbFlowCompVplPinAttr.add(tbFlowCompVplPinAttr);
                    }

                    if (listTbFlowCompVplPinAttr.size() > 0) {
                        tbFlowCompVplPinAttrDao.insertTbFlowCompVplPinAttrBatch(listTbFlowCompVplPinAttr);
                    }
                }

                tbTaskVersion.setComp_code(tempComp);
                /**
                 //20250314 增加一个判断,判断该料号是否可以创建修改流程
                 //那要先查询是否有正在审核的流程
                 List<TbTaskVersion> taskVersionList = tbTaskVersionDao.getTaskVersionByCompCode2(tempComp,"device",3);
                 if(taskVersionList!=null&&taskVersionList.size()>0)
                 {
                 return ResultUtil.error(500, "当前料号已经创建了该流程,流程编号为:"+taskVersionList.get(0).getFlow_no()+"", "", null);
                 }

                 //没有正在审核的流程,那就去数据库查当前最新版本的device信息
                 //如果没查到的话,那就是要查vpl流程了.
                 List<TbTaskVersion> taskVersionList2 = tbTaskVersionDao.getTaskVersionByCompCode3(tempComp,"device",3);

                 boolean isOk=false;
                 if(taskVersionList2!=null&&taskVersionList2.size()>0)
                 {
                 isOk=true;
                 }
                 else
                 {
                 //没查到,那就是查vpl流程了
                 List<TbTaskVersion> taskVersionList3 = tbTaskVersionDao.getTaskVersionByCompCode3(tempComp,"vpl",3);
                 if(taskVersionList3!=null&&taskVersionList3.size()>0)
                 {
                 isOk=true;
                 }
                 }

                 if(!isOk)
                 {
                 //没有查到,那就是没有创建过流程
                 return ResultUtil.error(500, "该料号需要走新建VPL流程", "", null);
                 }
                 */
            }

            List<TbTaskTemplateData> resultList = new ArrayList<>();
            //处理版本明细表数据
            if (!tempTemplateName.isEmpty()) {
                List<TbTemplateVersion> listVersion = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplateName);

                if (listVersion != null && listVersion.size() > 0) {
                    TbTemplateVersion tbTemplateVersion = listVersion.get(0);

                    List<TbTemplate> listTemplate = tbTemplateDao.getTbTemplateByVersion(tempTemplateName, tbTemplateVersion.getVersion());
                    if (listTemplate != null && listTemplate.size() > 0) {
                        //先转成TbTaskTemplateData
                        String final_flow_no = _flow_no;

                        List<TbTaskTemplateData> listTaskTemplateData = listTemplate.stream()
                                .map(template -> {
                                    TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                                    taskTemplateData.setFlow_no(final_flow_no);
                                    taskTemplateData.setFlow_level(1);
                                    taskTemplateData.setVersion(template.getVersion());
                                    taskTemplateData.setTemplate_type(template.getTemplate_type());
                                    taskTemplateData.setParent_id(template.getParent_id());
                                    taskTemplateData.setParam_name(template.getParam_name());
                                    taskTemplateData.setParam_name_en(template.getParam_name_en());
                                    taskTemplateData.setParam_key(template.getParam_key());
                                    taskTemplateData.setParent_param_key(template.getParent_param_key());
                                    taskTemplateData.setParam_type(template.getParam_type());
                                    taskTemplateData.setLevel(template.getLevel());
                                    taskTemplateData.setSelect_level(template.getSelect_level());
                                    taskTemplateData.setParent_select_id(template.getParent_select_id());
                                    taskTemplateData.setTip(template.getTip());
                                    taskTemplateData.setRemark(template.getRemark());
                                    taskTemplateData.setSort(template.getSort());
                                    taskTemplateData.setIs_value(template.getIs_value());
                                    return taskTemplateData;
                                })
                                //.filter(taskTemplateData -> taskTemplateData.getIs_value() == 2)
                                .collect(Collectors.toList());

                        if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                            resultList = getValuesFromJson("", jsonObject, listTaskTemplateData);
                        } else {
                            return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                        }
                    } else {
                        return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                    }

                } else {
                    return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                }
            } else {
                return ResultUtil.error(500, "flow_type 参数不正确", "", null);
            }
            //写入明细数据表
            tbTaskTemplateDataDao.insertTaskTemplateDataBatch(resultList);

            //新增处理design的逻辑数据
            if (_flow_type.equals("design")) {
                JSONArray keyArray = jsonObject.getJSONArray("keyList");

                JSONObject jb = new JSONObject();
                jb.put("knowledge_base_key", tbFlowProcessMain.getKnowledge_base_key());

                keyArray = new JSONArray();
                keyArray.add(jb);

                JSONArray logicArray = jsonObject.getJSONArray("logics");
                String userId = UserHeaderHolder.getUserId();
                Date now = new Date();

                if (keyArray != null && !keyArray.isEmpty()) {
                    List<TbKnowledgeBasePushLogic> logics = new ArrayList<>();
                    int sort = 0;
                    for (Object o : logicArray) {
                        JSONObject obj = (JSONObject) o;
                        TbKnowledgeBasePushLogic logic = new TbKnowledgeBasePushLogic();
                        logic.setBoardParamTypeName(obj.getString("boardParamTypeName"));
                        logic.setBoardParamName(obj.getString("boardParamName"));
                        logic.setBoardParamId(obj.getInteger("boardParamId"));
                        logic.setBoardParamKey(obj.getString("boardParamKey"));
                        logic.setBoardParamTypeId(obj.getInteger("boardParamTypeId"));
                        logic.setLogicRule(obj.getInteger("logicRule"));
                        logic.setLogicValue(obj.getString("logicValue"));
                        logic.setSort(sort++);
                        logic.setCreate_time(now);
                        logic.setCreate_user(userId);
                        logics.add(logic);
                    }
                    List<String> baseKeys = convertKeyListToStringList(keyArray, "knowledge_base_key");

                    queryKnowledgeBaseDataService.insertOrUpdateKnowledgeBaseLogic(logics, baseKeys);
                }
            }
        }

        if (_flow_type.equals("vpl")) {
            //vpl分5个流程
            //新建流程,获取pdm表中的数据,把信息都带过来
            //那我就默认他数据已经带过来了
            //获取第一个节点的对象名字叫compVplPdm
            //第一个节点流程
            String tempPkgNamePdm = "";
            String temps1partnumber = "";
            JSONArray compVplPdms = jsonObject.getJSONArray("compVplPdm");
            if (compVplPdms != null) {

                List<TbFlowCompVplPdm> listTbFlowCompVplPdm = new ArrayList<>();
                for (int i = 0; i < compVplPdms.size(); i++) {
                    JSONObject compVplPdm = compVplPdms.getJSONObject(i);

                    TbFlowCompVplPdm tbFlowCompVplPdm = new TbFlowCompVplPdm();
                    tbFlowCompVplPdm.setFlow_no(_flow_no);
                    tbFlowCompVplPdm.setFlow_level(1);
                    tbFlowCompVplPdm.setCreate_time(new Date());
                    tbFlowCompVplPdm.setCreate_user(_tempCreater);

                    String documentName = compVplPdm.getString("DocumentName");
                    String s1partnumber = compVplPdm.getString("s1partnumber");
                    temps1partnumber = s1partnumber;
                    String S1PCBENCPFILENAME = compVplPdm.getString("S1PCBENCPFILENAME");
                    tempPkgNamePdm = S1PCBENCPFILENAME;
                    String s1partdescelements = compVplPdm.getString("s1partdescelements");
                    String h3productline = compVplPdm.getString("h3productline");
                    String h3product = compVplPdm.getString("h3product");
                    String priority = compVplPdm.getString("priority");

                    //s1partnumber编号不能为空
                    if (s1partnumber == null || s1partnumber.isEmpty()) {
                        return ResultUtil.error(500, "PART编码不可以为空", "", null);
                    }

                    PdmNewPartApplication pdmNewPartApplication = new PdmNewPartApplication();
                    pdmNewPartApplication.setS1partnumber(s1partnumber);
                    pdmNewPartApplication.setDocumentName(documentName);
                    //增加一个判断.如果料号和PDM流程单号没有查到数据的话,就认为是垃圾数据,返回报错
                    //List<PdmNewPartApplication> pdmNewPartApplicationList = pdmNewPartApplicationDao.getPdmNewPartApplicationList(pdmNewPartApplication);

                    //if (pdmNewPartApplicationList == null || pdmNewPartApplicationList.size() <= 0) {
                    //    return ResultUtil.error(500, "PDM中未查询到有效信息,请刷新页面重试", "", null);
                    //}

                    //增加判断,查询是否有任何一条进行中的vpl的任务
                    List<TbTaskVersion> taskVersionList3 = tbTaskVersionDao.getTaskVersionByCompCode4(temps1partnumber, "vpl");
                    if (taskVersionList3 != null && taskVersionList3.size() > 0) {
                        return ResultUtil.error(500, "该料号已经存在进行中的VPL任务,流程编码为:" + taskVersionList3.get(0).getFlow_no() + "", "", null);
                    }

                    tbTaskVersion.setComp_code(s1partnumber);
                    //判断后加,预留
                    tbFlowCompVplPdm.setDocumentName(documentName);
                    tbFlowCompVplPdm.setS1partnumber(s1partnumber);
                    tbFlowCompVplPdm.setS1PCBENCPFILENAME(S1PCBENCPFILENAME);
                    tbFlowCompVplPdm.setS1partdescelements(s1partdescelements);
                    tbFlowCompVplPdm.setH3productline(h3productline);
                    tbFlowCompVplPdm.setH3product(h3product);
                    tbFlowCompVplPdm.setPriority(priority);

                    listTbFlowCompVplPdm.add(tbFlowCompVplPdm);
                }

                if (listTbFlowCompVplPdm.size() > 0) {
                    tbFlowCompVplPdmDao.insertTbFlowCompVplPdmBatch(listTbFlowCompVplPdm);
                }
            } else {
                return ResultUtil.error(500, "compVplPdm 参数不正确", "", null);
            }

            //获取第二个节点的对象名字叫compManufacturer
            JSONArray compManufacturerArray = jsonObject.getJSONArray("compManufacturer");

            if (compManufacturerArray != null && compManufacturerArray.size() > 0) {
                List<TbFlowCompManufacturer> listTbFlowCompManufacturer = new ArrayList<>();
                for (int i = 0; i < compManufacturerArray.size(); i++) {
                    JSONObject compManufacturer = compManufacturerArray.getJSONObject(i);

                    TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                    tbFlowCompManufacturer.setFlow_no(_flow_no);
                    tbFlowCompManufacturer.setFlow_level(1);
                    tbFlowCompManufacturer.setCreate_time(new Date());
                    tbFlowCompManufacturer.setCreate_user(_tempCreater);

                    String manufacturer = compManufacturer.getString("manufacturer");
                    String manufacturer_type = compManufacturer.getString("manufacturer_type");
                    String data_sources = compManufacturer.getString("data_sources");
                    //String comp_resource = compManufacturer.getString("comp_resource");

                    //其他器件资料是上传文件对象
                    Object comp_resourceType = compManufacturer.get("comp_resource");
                    if (comp_resourceType instanceof JSONArray) {
                        JSONArray comp_resource_filesArray = compManufacturer.getJSONArray("comp_resource") == null ? null : compManufacturer.getJSONArray("comp_resource");

                        if (comp_resource_filesArray != null) {
                            List<String> keyList = new ArrayList<>();

                            for (int j = 0; j < comp_resource_filesArray.size(); j++) {
                                JSONObject comp_resource_files = comp_resource_filesArray.getJSONObject(j);

                                String _param_key = String.valueOf(UUID.randomUUID());

                                keyList.add(_param_key);
                                //tbFlowCompManufacturer.setComp_resource(_param_key);
                                //updateParam.setVpl_model_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(1);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = comp_resource_files.get("file_name") == null ? null : comp_resource_files.get("file_name").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(comp_resource_files.get("picRelatePath") == null ? null : comp_resource_files.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(comp_resource_files.get("secretKey") == null ? null : comp_resource_files.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(comp_resource_files.get("fileSid") == null ? null : comp_resource_files.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }

                            if (keyList != null && keyList.size() > 0) {
                                tbFlowCompManufacturer.setComp_resource(String.join(",", keyList));
                            }


                        }
                    }

                    tbFlowCompManufacturer.setManufacturer(manufacturer);
                    tbFlowCompManufacturer.setManufacturer_type(manufacturer_type);
                    tbFlowCompManufacturer.setData_sources(data_sources);
                    tbFlowCompManufacturer.setComp_code(temps1partnumber);

                    listTbFlowCompManufacturer.add(tbFlowCompManufacturer);
                }
                if (listTbFlowCompManufacturer != null && listTbFlowCompManufacturer.size() > 0) {
                    tbFlowCompManufacturerDao.insertTbFlowCompManufacturerBatch(listTbFlowCompManufacturer);
                }
            }

            //第二个节点流程

            //第三个节点流程
            //tempPkgNamePdm
            //先去获取封装库的信息,看有没有数据
            //List<Mpackage> listMpackage = mpackageDao.getMpackageByPkgName(tempPkgNamePdm);
            List<vVplPackage> vVplPackageList = _vVplPackageDao.getvVplPackage(tempPkgNamePdm);
            if (vVplPackageList != null && vVplPackageList.size() > 0) {
                //有数据的话就直接带到流程里面去
                //Mpackage mpackage = listMpackage.get(0);
                vVplPackage mpackage = vVplPackageList.get(0);

                TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                tbFlowCompPkg.setFlow_no(_flow_no);
                tbFlowCompPkg.setFlow_level(3);
                tbFlowCompPkg.setCreate_time(new Date());
                tbFlowCompPkg.setCreate_user(_tempCreater);
                tbFlowCompPkg.setPkg_name(tempPkgNamePdm);

                tbFlowCompPkg.setAssembly_type(mpackage.getAssembly_type());
                tbFlowCompPkg.setFoot_num(mpackage.getFoot_num());
                //tbFlowCompPkg.setIs_orientation(mpackage.getIs_orientation());
                tbFlowCompPkg.setBody_length(mpackage.getBody_length());
                tbFlowCompPkg.setBody_width(mpackage.getBody_width());
                tbFlowCompPkg.setPad_airgap_min(mpackage.getPad_airgap_min());
                tbFlowCompPkg.setPitch_o2c_x(mpackage.getPitch_o2c_x());
                tbFlowCompPkg.setPitch_o2c_y(mpackage.getPitch_o2c_y());
                tbFlowCompPkg.setIs_size_not_fit(mpackage.getIs_size_not_fit());
                tbFlowCompPkg.setIs_grid_design(mpackage.getIs_grid_design());
                tbFlowCompPkg.setIs_twins_design(mpackage.getIs_twins_design());
                tbFlowCompPkg.setIs_special_design(mpackage.getIs_special_design());
                tbFlowCompPkg.setIs_window_open(mpackage.getIs_window_open());
                tbFlowCompPkg.setIs_small_air_gap(mpackage.getIs_small_air_gap());
                //tbFlowCompPkg.setIs_vpl_model_imported("是");
                tbFlowCompPkg.setIs_pkg_imported("否");
                tbFlowCompPkg.setIs_required_eda_lib("否");
                tbFlowCompPkg.setIs_vpl_parameters_imported("是");
                tbFlowCompPkg.setIs_from_vpl("Y");

                List<TbFlowCompPkg> listTbFlowCompPkg = new ArrayList<>();
                listTbFlowCompPkg.add(tbFlowCompPkg);

                tbFlowCompPkgDao.insertTbFlowCompPkgBatch(listTbFlowCompPkg);

            } else {
                TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                tbFlowCompPkg.setFlow_no(_flow_no);
                tbFlowCompPkg.setFlow_level(3);
                tbFlowCompPkg.setCreate_time(new Date());
                tbFlowCompPkg.setCreate_user(_tempCreater);
                tbFlowCompPkg.setPkg_name(tempPkgNamePdm);
                //tbFlowCompPkg.setIs_vpl_model_imported("是");
                tbFlowCompPkg.setIs_vpl_parameters_imported("是");
                tbFlowCompPkg.setIs_pkg_imported("是");
                tbFlowCompPkg.setIs_required_eda_lib("是");

                List<TbFlowCompPkg> listTbFlowCompPkg = new ArrayList<>();
                listTbFlowCompPkg.add(tbFlowCompPkg);

                tbFlowCompPkgDao.insertTbFlowCompPkgBatch(listTbFlowCompPkg);
            }

            //第四个节点流程
            List<TbTaskTemplateData> resultList = new ArrayList<>();
            //处理版本明细表数据
            if (!tempTemplateName.isEmpty()) {
                List<TbTemplateVersion> listVersion = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplateName);

                if (listVersion != null && listVersion.size() > 0) {
                    TbTemplateVersion tbTemplateVersion = listVersion.get(0);

                    List<TbTemplate> listTemplate = tbTemplateDao.getTbTemplateByVersion(tempTemplateName, tbTemplateVersion.getVersion());
                    if (listTemplate != null && listTemplate.size() > 0) {
                        //先转成TbTaskTemplateData
                        String final_flow_no = _flow_no;

                        List<TbTaskTemplateData> listTaskTemplateData = listTemplate.stream()
                                .map(template -> {
                                    TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                                    taskTemplateData.setFlow_no(final_flow_no);
                                    taskTemplateData.setFlow_level(4);
                                    taskTemplateData.setVersion(template.getVersion());
                                    taskTemplateData.setTemplate_type(template.getTemplate_type());
                                    taskTemplateData.setParent_id(template.getParent_id());
                                    taskTemplateData.setParam_name(template.getParam_name());
                                    taskTemplateData.setParam_name_en(template.getParam_name_en());
                                    taskTemplateData.setParam_key(template.getParam_key());
                                    taskTemplateData.setParent_param_key(template.getParent_param_key());
                                    taskTemplateData.setParam_type(template.getParam_type());
                                    taskTemplateData.setLevel(template.getLevel());
                                    taskTemplateData.setSelect_level(template.getSelect_level());
                                    taskTemplateData.setParent_select_id(template.getParent_select_id());
                                    taskTemplateData.setTip(template.getTip());
                                    taskTemplateData.setRemark(template.getRemark());
                                    taskTemplateData.setSort(template.getSort());
                                    taskTemplateData.setIs_value(template.getIs_value());
                                    return taskTemplateData;
                                })
                                //.filter(taskTemplateData -> taskTemplateData.getIs_value() == 2)
                                .collect(Collectors.toList());

                        if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                            resultList = getValuesFromJson("", jsonObject, listTaskTemplateData);
                        } else {
                            return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                        }
                    } else {
                        return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                    }

                } else {
                    return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                }
            } else {
                return ResultUtil.error(500, "flow_type 参数不正确", "", null);
            }
            //写入明细数据表
            tbTaskTemplateDataDao.insertTaskTemplateDataBatch(resultList);

            TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
            tbFlowCompVpl.setFlow_no(_flow_no);
            tbFlowCompVpl.setFlow_level(4);
            tbFlowCompVpl.setComp_code(temps1partnumber);
            tbFlowCompVpl.setCreate_user(_tempCreater);
            tbFlowCompVpl.setCreate_time(new Date());

            List<TbFlowCompVpl> listTbFlowCompVpl = new ArrayList<>();
            listTbFlowCompVpl.add(tbFlowCompVpl);

            tbFlowCompVplDao.insertTbFlowCompVplBatch(listTbFlowCompVpl);
            //第五个节点流程

        }

        //流程主表
        tbFlowProcessMainDao.insertFlowProcessMain(tbFlowProcessMain);
        //流程明细表
        tbFlowProcessDetailDao.insertFlowTemplateBatch(listFlowTemplate);
        //版本主表
        tbTaskVersionDao.insertTaskVersion(tbTaskVersion);

        return ResultUtil.success(_flow_no);
    }

    //@Transactional(transactionManager = "MysqlTransactionManager7")
    public Result handleUpdateAndCommit(String _flow_no, JSONObject jsonObject, String type, String flow_type, boolean is_need_knowledge_base, boolean is_send_mail, boolean is_need_model, String handleVpl) {
        try {
            List<TbTaskTemplateData> resultList = new ArrayList<>();
            //1、处理版本明细表数据
            //先转成TbTaskTemplateData
            String final_flow_no = _flow_no;

            //获取Json中传过来的人员流程信息
            Integer _flow_level = jsonObject.getInteger("flow_level");

            //获取flow_info对象
            JSONObject flow_info = jsonObject.getJSONObject("flowInfo");
            //如果为空的话就报错
            if (flow_info == null) {
                throw new Exception("节点flowInfo信息不可以为空");
                //return ResultUtil.error(500, "节点flowInfo信息为空", "", null);
            }

            //20250827增加防呆操作
            List<TbFlowProcessMain> tbFlowProcessMainBaseKey = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);
            if (tbFlowProcessMainBaseKey == null || tbFlowProcessMainBaseKey.size() == 0) {
                throw new Exception("未查询到流程信息,请刷新");
            }
            TbFlowProcessMain tbFlowProcessMain1 = tbFlowProcessMainBaseKey.get(0);

            if (_flow_level != tbFlowProcessMain1.getNow_level()) {
                throw new Exception("当前流程节点不正确,请刷新");
            }

            //20250320 新增逻辑,在保存流程的时候,去更新流程上的知识库key信息
            String _knowledge_base_key = jsonObject.getString("knowledge_base_key");
            //这个时候的key不可能为空的,如果为空了就是流程异常,或者没传,那么 把这个情况剔除
            if (_knowledge_base_key == null || _knowledge_base_key.isEmpty()) {
                //为空有可能是直接提交的,这个时候需要去查询一下流程主表,去查一下这个流程号上的key

                if (tbFlowProcessMainBaseKey != null && tbFlowProcessMainBaseKey.size() > 0) {

                    _knowledge_base_key = tbFlowProcessMain1.getKnowledge_base_key();
                } else {
                    throw new Exception("knowledge_base_key不可以为空");
                    //return ResultUtil.error(500, "knowledge_base_key不可以为空", "", null);
                }
            } else {
                //更新流程主表
                TbFlowProcessMain tbFlowProcessMainBaseKey2 = new TbFlowProcessMain();
                tbFlowProcessMainBaseKey2.setFlow_no(final_flow_no);
                tbFlowProcessMainBaseKey2.setKnowledge_base_key(_knowledge_base_key);

                tbFlowProcessMainDao.updateFlowProcessMain(tbFlowProcessMainBaseKey2);
            }
            //新增工艺规范库逻辑规则的处理方式.
            //新增处理design的逻辑数据
            if (flow_type.equals("design") && _flow_level == 1 && type.equals("commit")) {
                JSONArray keyArray = jsonObject.getJSONArray("keyList");
                //keyArray.add(_knowledge_base_key);

                JSONObject jb = new JSONObject();
                jb.put("knowledge_base_key", _knowledge_base_key);

                keyArray = new JSONArray();
                keyArray.add(jb);

                if (keyArray == null || keyArray.size() == 0) {
                    throw new Exception("工艺规程逻辑规则keyList不可以为空");
                }
                JSONArray logicArray = jsonObject.getJSONArray("logics");
                String userId = UserHeaderHolder.getUserId();
                Date now = new Date();

                List<TbKnowledgeBasePushLogic> logics = new ArrayList<>();
                int sort = 0;
                for (Object o : logicArray) {
                    JSONObject obj = (JSONObject) o;
                    TbKnowledgeBasePushLogic logic = new TbKnowledgeBasePushLogic();
                    logic.setBoardParamTypeName(obj.getString("boardParamTypeName"));
                    logic.setBoardParamName(obj.getString("boardParamName"));
                    logic.setBoardParamId(obj.getInteger("boardParamId"));
                    logic.setBoardParamKey(obj.getString("boardParamKey"));
                    logic.setBoardParamTypeId(obj.getInteger("boardParamTypeId"));
                    logic.setLogicRule(obj.getInteger("logicRule"));
                    logic.setLogicValue(obj.getString("logicValue"));
                    logic.setSort(sort++);
                    logic.setCreate_time(now);
                    logic.setCreate_user(userId);
                    logics.add(logic);
                }
                List<String> baseKeys = convertKeyListToStringList(keyArray, "knowledge_base_key");

                queryKnowledgeBaseDataService.insertOrUpdateKnowledgeBaseLogic(logics, baseKeys);
            }

            if ((flow_type.equals("design") || flow_type.equals("device")) || (flow_type.equals("vpl") && _flow_level == 4)) {

                if (is_need_model) {
                    List<TbTaskTemplateData> listTaskTemplateData = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(final_flow_no);
                    if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                        resultList = getValuesFromJson(_flow_no, jsonObject, listTaskTemplateData);
                    } else {
                        throw new Exception("未查询到该流程数据");
                        //return ResultUtil.error(500, "未查询到该流程数据", "", null);
                    }
                }
                //20250414 添加一个判断如果选的是需要工艺知识,那就多判断一个数据,如果正文描述信息没有条目的话,就提示报错
                //System.out.print(resultList[8].toString());
                //20250905 添加一个判断,如果是保存的话就不判断了
                if (flow_type.equals("vpl") && _flow_level == 4 && type.equals("commit")) {
                    Integer _is_need_knowledge_base = jsonObject.getInteger("is_need_knowledge_base");
                    if (_is_need_knowledge_base == 1) {
                        List<TbTaskTemplateData> filteredList = resultList.stream()
                                // 条件1：param_name等于"checklist"（空值安全判断）
                                .filter(obj -> "工艺知识checklist".equals(obj.getParam_name()))
                                // 条件2：row_sort不等于-1（需先判空）
                                .filter(obj -> obj.getRow_sort() != null && obj.getRow_sort() != -1)
                                // 新增条件3：param_value为空（包含null和空字符串）
                                //.filter(obj -> obj.getParam_value() == null || obj.getParam_value().isEmpty())
                                .collect(Collectors.toList());

                        if (filteredList == null || filteredList.size() <= 0) {
                            throw new Exception("工艺知识checklist不可以为空");
                        }

                        List<TbTaskTemplateData> filteredList2 = filteredList.stream()
                                .filter(obj -> obj.getParam_value() == null || obj.getParam_value().isEmpty())
                                .collect(Collectors.toList());

                        if (filteredList2 != null && filteredList2.size() > 0) {
                            throw new Exception("工艺知识checklist不可以为空");
                        }
                    }
                }

                if (flow_type.equals("device")) {
                    //写表
                    //compVpl
                    //compPkg
                    //compManufacturer
                    //compVplAttr
                    //compVplPinAttr
                    JSONArray compVpls = jsonObject.getJSONArray("compVpl");
                    if (compVpls != null) {
                        List<TbFlowCompVpl> listTbFlowCompVpl = new ArrayList<>();

                        for (int i = 0; i < compVpls.size(); i++) {
                            JSONObject compVpl = compVpls.getJSONObject(i);

                            TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                            tbFlowCompVpl.setFlow_no(_flow_no);
                            tbFlowCompVpl.setFlow_level(1);
                            tbFlowCompVpl.setUpdate_time(new Date());
                            tbFlowCompVpl.setUpdate_user(UserHeaderHolder.getUserId());

                            tbFlowCompVpl.setId(compVpl.getInteger("id"));
                            tbFlowCompVpl.setComp_code(compVpl.getString("comp_code"));
                            tbFlowCompVpl.setComp_type(compVpl.getString("comp_type"));
                            tbFlowCompVpl.setPkg_name(compVpl.getString("pkg_name"));
                            tbFlowCompVpl.setAssembly_type(compVpl.getString("assembly_type"));
                            tbFlowCompVpl.setComponent_high_max_vpl(compVpl.getString("component_high_max_vpl"));
                            tbFlowCompVpl.setComponent_high_max_pdm(compVpl.getString("component_high_max_pdm"));
                            tbFlowCompVpl.setIs_dense_comp(compVpl.getString("is_dense_comp"));
                            tbFlowCompVpl.setStress_properties(compVpl.getString("stress_properties"));
                            tbFlowCompVpl.setPin_high_max(compVpl.getString("pin_high_max"));
                            tbFlowCompVpl.setPin_high_min(compVpl.getString("pin_high_min"));
                            tbFlowCompVpl.setPastemask_thickness_max(compVpl.getString("pastemask_thickness_max"));
                            tbFlowCompVpl.setPastemask_thickness_min(compVpl.getString("pastemask_thickness_min"));
                            tbFlowCompVpl.setPth_diameter_min(compVpl.getString("pth_diameter_min"));
                            tbFlowCompVpl.setPin_min_pitch(compVpl.getString("pin_min_pitch"));
                            tbFlowCompVpl.setIs_tht_power(compVpl.getString("is_tht_power"));
                            tbFlowCompVpl.setIs_tht_capcitor(compVpl.getString("is_tht_capcitor"));
                            tbFlowCompVpl.setIs_glue(compVpl.getString("is_glue"));
                            tbFlowCompVpl.setIs_little_retentionforce(compVpl.getString("is_little_retentionforce"));

                            listTbFlowCompVpl.add(tbFlowCompVpl);
                        }

                        if (listTbFlowCompVpl.size() > 0) {

                            for (TbFlowCompVpl tbFlowCompVpl : listTbFlowCompVpl) {
                                tbFlowCompVplDao.updateTbFlowCompVpl(tbFlowCompVpl);
                            }

                        }
                    }

                    JSONArray compPkgs = jsonObject.getJSONArray("compPkg");
                    if (compPkgs != null) {
                        List<TbFlowCompPkg> listTbFlowCompPkg = new ArrayList<>();

                        for (int i = 0; i < compPkgs.size(); i++) {
                            JSONObject compPkg = compPkgs.getJSONObject(i);

                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                            tbFlowCompPkg.setFlow_no(_flow_no);
                            tbFlowCompPkg.setFlow_level(1);
                            tbFlowCompPkg.setUpdate_time(new Date());
                            tbFlowCompPkg.setUpdate_user(UserHeaderHolder.getUserId());

                            tbFlowCompPkg.setId(compPkg.getInteger("id"));
                            tbFlowCompPkg.setPkg_name(compPkg.getString("pkg_name"));
                            tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                            tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                            tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                            tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                            tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                            tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                            tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                            tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                            tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                            tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                            tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                            tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                            tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                            tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));

                            listTbFlowCompPkg.add(tbFlowCompPkg);
                        }

                        if (listTbFlowCompPkg.size() > 0) {
                            for (TbFlowCompPkg tbFlowCompPkg : listTbFlowCompPkg) {
                                tbFlowCompPkgDao.updateTbFlowCompPkg(tbFlowCompPkg);
                            }
                        }
                    }

                    JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");
                    if (compManufacturers != null) {
                        List<TbFlowCompManufacturer> listTbFlowCompManufacturer = new ArrayList<>();
                        for (int i = 0; i < compManufacturers.size(); i++) {
                            JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                            TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                            tbFlowCompManufacturer.setFlow_no(_flow_no);
                            tbFlowCompManufacturer.setFlow_level(1);
                            tbFlowCompManufacturer.setUpdate_time(new Date());
                            tbFlowCompManufacturer.setUpdate_user(UserHeaderHolder.getUserId());

                            tbFlowCompManufacturer.setId(compManufacturer.getInteger("id"));
                            tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                            tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));
                            tbFlowCompManufacturer.setWeight(compManufacturer.getString("weight"));
                            tbFlowCompManufacturer.setCoplanarity(compManufacturer.getString("coplanarity"));
                            tbFlowCompManufacturer.setStandoff(compManufacturer.getString("standoff"));
                            tbFlowCompManufacturer.setSolder_tg_max(compManufacturer.getString("solder_tg_max"));
                            tbFlowCompManufacturer.setBga_height_min(compManufacturer.getString("bga_height_min"));
                            tbFlowCompManufacturer.setUnbd_thickness_min(compManufacturer.getString("unbd_thickness_min"));
                            tbFlowCompManufacturer.setBoard_thickness_min(compManufacturer.getString("board_thickness_min"));
                            tbFlowCompManufacturer.setBoard_thickness_max(compManufacturer.getString("board_thickness_max"));
                            tbFlowCompManufacturer.setIs_secd_reflow_drop(compManufacturer.getString("is_secd_reflow_drop"));
                            tbFlowCompManufacturer.setThermal_contact_dimension(compManufacturer.getString("thermal_contact_dimension"));

                            listTbFlowCompManufacturer.add(tbFlowCompManufacturer);
                        }
                        if (listTbFlowCompManufacturer.size() > 0) {

                            for (TbFlowCompManufacturer tbFlowCompManufacturer : listTbFlowCompManufacturer) {
                                tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                            }

                        }
                    }

                    JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");
                    if (compVplAttrs != null) {
                        List<TbFlowCompVplAttr> listTbFlowCompVplAttr = new ArrayList<>();
                        for (int i = 0; i < compVplAttrs.size(); i++) {
                            JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                            TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();
                            tbFlowCompVplAttr.setFlow_no(_flow_no);
                            tbFlowCompVplAttr.setFlow_level(1);
                            tbFlowCompVplAttr.setUpdate_time(new Date());
                            tbFlowCompVplAttr.setUpdate_user(UserHeaderHolder.getUserId());

                            tbFlowCompVplAttr.setId(compVplAttr.getInteger("id"));
                            tbFlowCompVplAttr.setManufacturer_type(compVplAttr.getString("manufacturer_type"));
                            tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                            tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                            tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));
                            tbFlowCompVplAttr.setCoplanarity(compVplAttr.getString("coplanarity"));
                            tbFlowCompVplAttr.setWeight(compVplAttr.getString("weight"));
                            tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                            tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                            tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                            tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                            tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                            tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                            tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                            tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                            tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                            tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));
                            tbFlowCompVplAttr.setStandoff(compVplAttr.getString("standoff"));
                            tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                            tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                            tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                            tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                            tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                            tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                            tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                            listTbFlowCompVplAttr.add(tbFlowCompVplAttr);
                        }
                        if (listTbFlowCompVplAttr.size() > 0) {
                            for (TbFlowCompVplAttr tbFlowCompVplAttr : listTbFlowCompVplAttr) {
                                tbFlowCompVplAttrDao.updateTbFlowCompVplAttr(tbFlowCompVplAttr);
                            }

                        }
                    }

                    JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                    if (compVplPinAttrs != null) {
                        List<TbFlowCompVplPinAttr> listTbFlowCompVplPinAttr = new ArrayList<>();
                        for (int i = 0; i < compVplPinAttrs.size(); i++) {
                            JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);
                            TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();
                            tbFlowCompVplPinAttr.setFlow_no(_flow_no);
                            tbFlowCompVplPinAttr.setFlow_level(1);
                            tbFlowCompVplPinAttr.setUpdate_time(new Date());
                            tbFlowCompVplPinAttr.setUpdate_user(UserHeaderHolder.getUserId());

                            tbFlowCompVplPinAttr.setId(compVplPinAttr.getInteger("id"));
                            tbFlowCompVplPinAttr.setMpn(compVplPinAttr.getString("mpn"));
                            tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                            tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                            tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                            tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                            tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                            tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                            tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                            tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                            tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                            tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                            tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                            tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                            tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                            tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                            tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                            tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                            listTbFlowCompVplPinAttr.add(tbFlowCompVplPinAttr);
                        }

                        if (listTbFlowCompVplPinAttr.size() > 0) {
                            for (TbFlowCompVplPinAttr tbFlowCompVplPinAttr : listTbFlowCompVplPinAttr) {
                                tbFlowCompVplPinAttrDao.updateTbFlowCompVplPinAttr(tbFlowCompVplPinAttr);
                            }
                        }
                    }
                }
            }
            //处理流程节点的信息更新审核人,设计人员

            //获取flow_info对象中的comments,flow_approver,designer
            String _comments = flow_info.getString("comments");
            String _flow_approver = flow_info.getString("flow_approver");
            String _designer = flow_info.getString("designer");
            String _vplCreateUser = flow_info.getString("vpl_create_user");
            String _is_vpl_parameters_checked = flow_info.getString("is_vpl_parameters_checked");
            Integer _is_need_knowledge_base = jsonObject.getInteger("is_need_knowledge_base");
            Integer _is_skip = jsonObject.getInteger("is_skip");

            //String other_resource = flow_info.getString("other_resource");
            //String cc = flow_info.getString("cc");
            //String difficulty = flow_info.getString("difficulty");
            //String equivalent_num = flow_info.getString("equivalent_num");

            //这边修改的其实是当前节点的下一个节点的信息,但是审核意见是当前节点的
            TbFlowProcessDetail updateParam = new TbFlowProcessDetail();
            updateParam.setUpdate_time(new Date());
            updateParam.setUpdate_user(UserHeaderHolder.getUserId());
            updateParam.setFlow_no(_flow_no);
            //updateParam.setFlow_approver(_flow_approver);

            updateParam.setComments(_comments);
            updateParam.setFlow_level(_flow_level);
            updateParam.setIs_vpl_parameters_checked(_is_vpl_parameters_checked);
            updateParam.setIs_need_knowledge_base(_is_need_knowledge_base);
            //updateParam.setIs_skip(_is_skip);
            //updateParam.setVpl_create_user(_vplCreateUser);
            //updateParam.setDesigner(_designer);
            //tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam);

            if (_flow_level == 1) {
                //如果审核人和工艺设计人员带到所有的节点里去
                TbFlowProcessDetail designerAndVplCreater = new TbFlowProcessDetail();
                designerAndVplCreater.setFlow_no(_flow_no);
                designerAndVplCreater.setUpdate_time(new Date());
                designerAndVplCreater.setVpl_create_user(_vplCreateUser);
                designerAndVplCreater.setDesigner(_designer);
                tbFlowProcessDetailDao.updateFlowProcessDetail2(designerAndVplCreater);
            }

            //审核人这个字段,永远都是下一个节点的审核人,但是实际上这边少了判断 是否是最后一个节点了,但是更新也无所谓.
            //增加一个判断,如果是commit的话,下一个节点审核人不允许为空
            if (type.equals("commit")) {
                if (_flow_approver == null || _flow_approver.equals("")) {
                    throw new Exception("提交时审核人不能为空");
                    //return ResultUtil.error(500, "提交时审核人不能为空", "", null);
                }
            }

            TbFlowProcessDetail updateParam2 = new TbFlowProcessDetail();
            updateParam2.setFlow_no(_flow_no);
            updateParam2.setFlow_approver(_flow_approver);
            updateParam2.setFlow_level(_flow_level + 1);
            updateParam2.setDesigner(_designer);
            updateParam2.setUpdate_time(new Date());
            updateParam2.setUpdate_user(UserHeaderHolder.getUserId());
            tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam2);

            //判断当前是否已经审批完成了
            List<TbFlowProcessDetail> list = tbFlowProcessDetailDao.getFlowProcessDetail(updateParam);

            if (list == null) {
                throw new Exception("未查询到该流程数据");
                //return ResultUtil.error(500, "未查询到该流程数据", "", null);
            } else {
                TbFlowProcessDetail tbFlowProcessDetail = list.get(0);
                if (tbFlowProcessDetail.getStatus() == 2) {
                    throw new Exception("该节点已审核完成");
                    //return ResultUtil.error(500, "该节点已审核完成", "", null);
                }
            }

            Result newData = new Result();

            if (type.equals("save")) {
                if (flow_type.equals("vpl")) {
                    //更新流程节点对象
                    //VPL流程一共有5个节点,第一个节点只是更新两张表
                    if (_flow_level == 1) {

                        //20250314 增加判断,第一和第三环节的责任人就是建库人员,那就是要去修改这两个节点的审核人
                        //20250318 去除第一节点的责任人修改
                        //TbFlowProcessDetail updateFlowApper1 = new TbFlowProcessDetail();
                        //updateFlowApper1.setUpdate_time(new Date());
                        //updateFlowApper1.setUpdate_user(UserHeaderHolder.getUserId());
                        //updateFlowApper1.setFlow_no(_flow_no);
                        //updateFlowApper1.setFlow_level(_flow_level);
                        //updateFlowApper1.setFlow_approver(_vplCreateUser);
                        //tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper1);

                        TbFlowProcessDetail updateFlowApper2 = new TbFlowProcessDetail();
                        updateFlowApper2.setUpdate_time(new Date());
                        updateFlowApper2.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper2.setFlow_no(_flow_no);
                        updateFlowApper2.setFlow_level(3);
                        updateFlowApper2.setFlow_approver(_vplCreateUser);
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper2);

                        //如果是第一个节点的话,还要去更新一下主节点上面的当前审核人,其实不更新也行
                        //TbFlowProcessMain tbFlowProcessMain=new TbFlowProcessMain();
                        //tbFlowProcessMainDao.updateFlowProcessMainForAuthorize(UserHeaderHolder.getUserId(),_flow_no,_flow_level);

                        TbFlowProcessDetail updateFlowApper3 = new TbFlowProcessDetail();
                        updateFlowApper3.setUpdate_time(new Date());
                        updateFlowApper3.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper3.setFlow_no(_flow_no);
                        updateFlowApper3.setFlow_level(4);
                        updateFlowApper3.setFlow_approver(_designer);
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper3);

                        //第一个节点更新三张表
                        //TbFlowCompVplPdm
                        //TbFlowCompManufacturer
                        //TbFlowProcessDetail
                        JSONArray compVplPdms = jsonObject.getJSONArray("compVplPdm");
                        for (int i = 0; i < compVplPdms.size(); i++) {
                            JSONObject compVplPdm = compVplPdms.getJSONObject(i);
                            TbFlowCompVplPdm tbFlowCompVplPdm = new TbFlowCompVplPdm();

                            tbFlowCompVplPdm.setId(compVplPdm.getInteger("id"));

                            tbFlowCompVplPdm.setPriority(compVplPdm.getString("priority"));

                            tbFlowCompVplPdmDao.updateTbFlowCompVplPdm(tbFlowCompVplPdm);
                        }
                        JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");

                        if (handleVpl.equals("Y")) {
                            for (int i = 0; i < compManufacturers.size(); i++) {
                                JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                                TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();

                                Integer _id = compManufacturer.getInteger("id");
                                tbFlowCompManufacturer.setId(_id);
                                tbFlowCompManufacturer.setUpdate_time(new Date());
                                tbFlowCompManufacturer.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                                tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));

                                //tbFlowCompManufacturer.setComp_resource(compManufacturer.getString("comp_resource"));

                                Object comp_resourceType = compManufacturer.get("comp_resource");
                                if (comp_resourceType instanceof JSONArray) {
                                    JSONArray comp_resource_filesArray = compManufacturer.getJSONArray("comp_resource") == null ? null : compManufacturer.getJSONArray("comp_resource");

                                    if (comp_resource_filesArray != null) {
                                        List<String> keyList = new ArrayList<>();

                                        for (int j = 0; j < comp_resource_filesArray.size(); j++) {
                                            JSONObject comp_resource_files = comp_resource_filesArray.getJSONObject(j);

                                            String _param_key = String.valueOf(UUID.randomUUID());

                                            keyList.add(_param_key);
                                            //tbFlowCompManufacturer.setComp_resource(_param_key);
                                            //updateParam.setVpl_model_excel(_param_key);

                                            TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                            tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                            tbKnowledgeBaseFile.setFlow_level(1);
                                            tbKnowledgeBaseFile.setParam_key(_param_key);

                                            String filename = comp_resource_files.get("file_name") == null ? null : comp_resource_files.get("file_name").toString();
                                            tbKnowledgeBaseFile.setFile_name(filename);
                                            tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                            tbKnowledgeBaseFile.setFile_relate_path(comp_resource_files.get("picRelatePath") == null ? null : comp_resource_files.get("picRelatePath").toString());
                                            tbKnowledgeBaseFile.setFile_type(3);
                                            tbKnowledgeBaseFile.setSecret_key(comp_resource_files.get("secretKey") == null ? null : comp_resource_files.get("secretKey").toString());
                                            tbKnowledgeBaseFile.setFile_sid(comp_resource_files.get("fileSid") == null ? null : comp_resource_files.get("fileSid").toString());

                                            List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                            tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                            tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                        }

                                        if (keyList != null && keyList.size() > 0) {
                                            tbFlowCompManufacturer.setComp_resource(String.join(",", keyList));
                                        }


                                    }
                                }

                                if (_id == 0) {
                                    tbFlowCompManufacturer.setFlow_no(_flow_no);
                                    tbFlowCompManufacturer.setFlow_level(1);

                                    List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                    tbFlowCompManufacturerList.add(tbFlowCompManufacturer);

                                    tbFlowCompManufacturerDao.insertTbFlowCompManufacturerBatch(tbFlowCompManufacturerList);
                                } else {
                                    tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                                }
                            }

                            String other_resource = flow_info.getString("other_resource");
                            String cc = flow_info.getString("cc");

                            Object other_resource_filesType = flow_info.get("other_resource_files");
                            if (other_resource_filesType instanceof JSONArray) {
                                JSONArray other_resource_filesArray = flow_info.getJSONArray("other_resource_files") == null ? null : flow_info.getJSONArray("other_resource_files");
                                if (other_resource_filesArray != null) {
                                    List<String> keyList = new ArrayList<>();

                                    for (int i = 0; i < other_resource_filesArray.size(); i++) {

                                        JSONObject other_resource_files = other_resource_filesArray.getJSONObject(i);

                                        String _param_key = String.valueOf(UUID.randomUUID());
                                        keyList.add(_param_key);
                                        //updateParam.setOther_resource_files(_param_key);
                                        //updateParam.setVpl_model_excel(_param_key);
                                        TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                        tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                        tbKnowledgeBaseFile.setFlow_level(1);
                                        tbKnowledgeBaseFile.setParam_key(_param_key);

                                        String filename = other_resource_files.get("file_name") == null ? null : other_resource_files.get("file_name").toString();
                                        tbKnowledgeBaseFile.setFile_name(filename);
                                        tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                        tbKnowledgeBaseFile.setFile_relate_path(other_resource_files.get("picRelatePath") == null ? null : other_resource_files.get("picRelatePath").toString());
                                        tbKnowledgeBaseFile.setFile_type(3);
                                        tbKnowledgeBaseFile.setSecret_key(other_resource_files.get("secretKey") == null ? null : other_resource_files.get("secretKey").toString());
                                        tbKnowledgeBaseFile.setFile_sid(other_resource_files.get("fileSid") == null ? null : other_resource_files.get("fileSid").toString());

                                        List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                        tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                        tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                    }

                                    if (keyList != null && keyList.size() > 0) {
                                        updateParam.setOther_resource_files(String.join(",", keyList));
                                    }

                                }
                            }


                            updateParam.setOther_resource(other_resource);
                            updateParam.setCc(cc);
                        }

                        //tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam);
                    }

                    if (_flow_level == 2) {
                        Object vpl_attr_excelType = jsonObject.get("vpl_attr_excel");
                        if (vpl_attr_excelType instanceof JSONObject) {
                            //处理两个文件列表的对象信息
                            JSONObject vpl_attr_excel = jsonObject.getJSONObject("vpl_attr_excel");
                            if (vpl_attr_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_attr_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_attr_excel.get("fileName") == null ? null : vpl_attr_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_attr_excel.get("picRelatePath") == null ? null : vpl_attr_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_attr_excel.get("secretKey") == null ? null : vpl_attr_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_attr_excel.get("fileSid") == null ? null : vpl_attr_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }

                        Object vpl_model_excelType = jsonObject.get("vpl_model_excel");
                        if (vpl_model_excelType instanceof JSONObject) {
                            JSONObject vpl_model_excel = jsonObject.getJSONObject("vpl_model_excel");
                            if (vpl_model_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_model_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_model_excel.get("fileName") == null ? null : vpl_model_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_model_excel.get("picRelatePath") == null ? null : vpl_model_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_model_excel.get("secretKey") == null ? null : vpl_model_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_model_excel.get("fileSid") == null ? null : vpl_model_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }

                        String max_Body_height = flow_info.getString("max_Body_height");
                        String max_Pin_length = flow_info.getString("max_Pin_length");
                        String min_Pin_length = flow_info.getString("min_Pin_length");

                        updateParam.setMax_Body_height(max_Body_height);
                        updateParam.setMax_Pin_length(max_Pin_length);
                        updateParam.setMin_Pin_length(min_Pin_length);

                        //修改两个属性数据
                        JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");
                        for (int i = 0; i < compVplAttrs.size(); i++) {
                            JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                            TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();

                            tbFlowCompVplAttr.setId(compVplAttr.getInteger("id"));
                            tbFlowCompVplAttr.setUpdate_time(new Date());
                            tbFlowCompVplAttr.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowCompVplAttr.setManufacturer_type(compVplAttr.getString("manufacturer_type"));
                            tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                            tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                            tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));
                            tbFlowCompVplAttr.setCoplanarity(compVplAttr.getString("coplanarity"));
                            tbFlowCompVplAttr.setWeight(compVplAttr.getString("weight"));
                            tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                            tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                            tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                            tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                            tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                            tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                            tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                            tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                            tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                            tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));
                            tbFlowCompVplAttr.setStandoff(compVplAttr.getString("standoff"));
                            tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                            tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                            tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                            tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                            tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                            tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                            tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                            tbFlowCompVplAttrDao.updateTbFlowCompVplAttr(tbFlowCompVplAttr);
                        }

                        JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                        for (int i = 0; i < compVplPinAttrs.size(); i++) {
                            JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);

                            TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();

                            tbFlowCompVplPinAttr.setId(compVplPinAttr.getInteger("id"));
                            tbFlowCompVplPinAttr.setUpdate_time(new Date());
                            tbFlowCompVplPinAttr.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                            tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                            tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                            tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                            tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                            tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                            tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                            tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                            tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                            tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                            tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                            tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                            tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                            tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                            tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                            tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                            tbFlowCompVplPinAttrDao.updateTbFlowCompVplPinAttr(tbFlowCompVplPinAttr);
                        }

                        //修改流程节点的数据
                        String difficulty = flow_info.getString("difficulty");
                        String equivalent_num = flow_info.getString("equivalent_num");
                        String supply_vpl_create_user = flow_info.getString("supply_vpl_create_user");

                        updateParam.setSupply_vpl_create_user(supply_vpl_create_user);
                        updateParam.setDifficulty(difficulty);
                        updateParam.setEquivalent_num(equivalent_num);

                        //tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam);
                    }

                    if (_flow_level == 3) {
                        Object vpl_pkg_excelType = jsonObject.get("vpl_pkg_excel");
                        if (vpl_pkg_excelType instanceof JSONObject) {
                            //处理两个文件列表的对象信息
                            JSONObject vpl_pkg_excel = jsonObject.getJSONObject("vpl_pkg_excel");
                            if (vpl_pkg_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_pkg_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_pkg_excel.get("fileName") == null ? null : vpl_pkg_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_pkg_excel.get("picRelatePath") == null ? null : vpl_pkg_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_pkg_excel.get("secretKey") == null ? null : vpl_pkg_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_pkg_excel.get("fileSid") == null ? null : vpl_pkg_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }


                        JSONArray compPkgs = jsonObject.getJSONArray("compPkg");

                        for (int i = 0; i < compPkgs.size(); i++) {
                            JSONObject compPkg = compPkgs.getJSONObject(i);
                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();

                            tbFlowCompPkg.setId(compPkg.getInteger("id"));
                            tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                            tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                            tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                            tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                            tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                            tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                            tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                            tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                            tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                            tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                            tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                            tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                            tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                            tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));
                            tbFlowCompPkg.setIs_vpl_model_imported(compPkg.getString("is_vpl_model_imported"));
                            tbFlowCompPkg.setIs_vpl_parameters_imported(compPkg.getString("is_vpl_parameters_imported"));
                            tbFlowCompPkg.setIs_pkg_imported(compPkg.getString("is_pkg_imported"));
                            tbFlowCompPkg.setIs_required_eda_lib(compPkg.getString("is_required_eda_lib"));
                            tbFlowCompPkg.setIs_required_vpl_pkg(compPkg.getString("is_required_vpl_pkg"));
                            tbFlowCompPkg.setTimeliness(compPkg.getString("timeliness"));
                            tbFlowCompPkg.setQuality(compPkg.getString("quality"));
                            tbFlowCompPkg.setOverall_evaluation(compPkg.getString("overall_evaluation"));
                            tbFlowCompPkg.setAttachment(compPkg.getString("attachment"));

                            tbFlowCompPkgDao.updateTbFlowCompPkg(tbFlowCompPkg);
                        }

                    }

                    if (_flow_level == 4) {
                        JSONArray compVpls = jsonObject.getJSONArray("compVpl");
                        if (compVpls != null) {
                            for (int i = 0; i < compVpls.size(); i++) {
                                JSONObject compVpl = compVpls.getJSONObject(i);

                                TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                tbFlowCompVpl.setUpdate_time(new Date());
                                tbFlowCompVpl.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVpl.setId(compVpl.getInteger("id"));
                                tbFlowCompVpl.setComp_code(compVpl.getString("comp_code"));
                                tbFlowCompVpl.setComp_type(compVpl.getString("comp_type"));
                                tbFlowCompVpl.setPkg_name(compVpl.getString("pkg_name"));
                                tbFlowCompVpl.setAssembly_type(compVpl.getString("assembly_type"));
                                tbFlowCompVpl.setComponent_high_max_vpl(compVpl.getString("component_high_max_vpl"));
                                tbFlowCompVpl.setComponent_high_max_pdm(compVpl.getString("component_high_max_pdm"));
                                tbFlowCompVpl.setIs_dense_comp(compVpl.getString("is_dense_comp"));
                                tbFlowCompVpl.setStress_properties(compVpl.getString("stress_properties"));
                                tbFlowCompVpl.setPin_high_max(compVpl.getString("pin_high_max"));
                                tbFlowCompVpl.setPin_high_min(compVpl.getString("pin_high_min"));
                                tbFlowCompVpl.setPastemask_thickness_max(compVpl.getString("pastemask_thickness_max"));
                                tbFlowCompVpl.setPastemask_thickness_min(compVpl.getString("pastemask_thickness_min"));
                                tbFlowCompVpl.setPth_diameter_min(compVpl.getString("pth_diameter_min"));
                                tbFlowCompVpl.setPin_min_pitch(compVpl.getString("pin_min_pitch"));
                                tbFlowCompVpl.setIs_tht_power(compVpl.getString("is_tht_power"));
                                tbFlowCompVpl.setIs_tht_capcitor(compVpl.getString("is_tht_capcitor"));
                                tbFlowCompVpl.setIs_glue(compVpl.getString("is_glue"));
                                tbFlowCompVpl.setIs_little_retentionforce(compVpl.getString("is_little_retentionforce"));

                                tbFlowCompVplDao.updateTbFlowCompVpl(tbFlowCompVpl);
                            }
                        }

                        JSONArray compPkgs = jsonObject.getJSONArray("compPkg");
                        if (compPkgs != null) {
                            for (int i = 0; i < compPkgs.size(); i++) {
                                JSONObject compPkg = compPkgs.getJSONObject(i);

                                TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                                tbFlowCompPkg.setUpdate_time(new Date());
                                tbFlowCompPkg.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompPkg.setId(compPkg.getInteger("id"));
                                tbFlowCompPkg.setPkg_name(compPkg.getString("pkg_name"));
                                tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                                tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                                tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                                tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                                tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                                tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                                tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                                tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                                tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                                tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                                tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                                tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                                tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                                tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));

                                tbFlowCompPkgDao.updateTbFlowCompPkg(tbFlowCompPkg);
                            }
                        }

                        JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");
                        if (compManufacturers != null) {
                            for (int i = 0; i < compManufacturers.size(); i++) {
                                JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                                TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                                tbFlowCompManufacturer.setUpdate_time(new Date());
                                tbFlowCompManufacturer.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompManufacturer.setId(compManufacturer.getInteger("id"));
                                tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                                tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));
                                tbFlowCompManufacturer.setWeight(compManufacturer.getString("weight"));
                                tbFlowCompManufacturer.setCoplanarity(compManufacturer.getString("coplanarity"));
                                tbFlowCompManufacturer.setStandoff(compManufacturer.getString("standoff"));
                                tbFlowCompManufacturer.setSolder_tg_max(compManufacturer.getString("solder_tg_max"));
                                tbFlowCompManufacturer.setBga_height_min(compManufacturer.getString("bga_height_min"));
                                tbFlowCompManufacturer.setUnbd_thickness_min(compManufacturer.getString("unbd_thickness_min"));
                                tbFlowCompManufacturer.setBoard_thickness_min(compManufacturer.getString("board_thickness_min"));
                                tbFlowCompManufacturer.setBoard_thickness_max(compManufacturer.getString("board_thickness_max"));
                                tbFlowCompManufacturer.setIs_secd_reflow_drop(compManufacturer.getString("is_secd_reflow_drop"));
                                tbFlowCompManufacturer.setThermal_contact_dimension(compManufacturer.getString("thermal_contact_dimension"));

                                tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                            }
                        }

                        JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");
                        if (compVplAttrs != null) {
                            for (int i = 0; i < compVplAttrs.size(); i++) {
                                JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                                TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();
                                tbFlowCompVplAttr.setUpdate_time(new Date());
                                tbFlowCompVplAttr.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVplAttr.setId(compVplAttr.getInteger("id"));
                                tbFlowCompVplAttr.setManufacturer_type(compVplAttr.getString("manufacturer_type"));
                                tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                                tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                                tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));
                                tbFlowCompVplAttr.setCoplanarity(compVplAttr.getString("coplanarity"));
                                tbFlowCompVplAttr.setWeight(compVplAttr.getString("weight"));
                                tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                                tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                                tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                                tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                                tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                                tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                                tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                                tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                                tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                                tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));
                                tbFlowCompVplAttr.setStandoff(compVplAttr.getString("standoff"));
                                tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                                tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                                tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                                tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                                tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                                tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                                tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                                tbFlowCompVplAttrDao.updateTbFlowCompVplAttr(tbFlowCompVplAttr);
                            }
                        }

                        JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                        if (compVplPinAttrs != null) {
                            for (int i = 0; i < compVplPinAttrs.size(); i++) {
                                JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);
                                TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();
                                tbFlowCompVplPinAttr.setUpdate_time(new Date());
                                tbFlowCompVplPinAttr.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVplPinAttr.setId(compVplPinAttr.getInteger("id"));
                                tbFlowCompVplPinAttr.setMpn(compVplPinAttr.getString("mpn"));
                                tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                                tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                                tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                                tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                                tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                                tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                                tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                                tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                                tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                                tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                                tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                                tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                                tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                                tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                                tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                                tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                                tbFlowCompVplPinAttrDao.updateTbFlowCompVplPinAttr(tbFlowCompVplPinAttr);
                            }
                        }
                    }

                    if (_flow_level == 5) {

                    }
                }

            }
            if (type.equals("commit")) {
                if (flow_type.equals("vpl")) {
                    if (_flow_level == 1) {
                        if (_vplCreateUser == null || _vplCreateUser.isEmpty()) {
                            throw new Exception("建库人员不能为空");
                            //return ResultUtil.error(500, "建库人员不能为空", "", null);
                        }

                        if (_designer == null || _designer.isEmpty()) {
                            throw new Exception("工艺设计人员不能为空");
                            //return ResultUtil.error(500, "工艺设计人员不能为空", "", null);
                        }

                        TbFlowProcessDetail tempUpdate = new TbFlowProcessDetail();
                        tempUpdate.setFlow_no(_flow_no);
                        tempUpdate.setFlow_level(_flow_level);
                        tempUpdate.setIs_skip(_is_skip);

                        tbFlowProcessDetailDao.updateFlowProcessDetail(tempUpdate);

                        //20250314 增加判断,第一和第三环节的责任人就是建库人员,那就是要去修改这两个节点的审核人
                        //TbFlowProcessDetail updateFlowApper1 = new TbFlowProcessDetail();
                        //updateFlowApper1.setUpdate_time(new Date());
                        //updateFlowApper1.setUpdate_user(UserHeaderHolder.getUserId());
                        //updateFlowApper1.setFlow_no(_flow_no);
                        //updateFlowApper1.setFlow_level(_flow_level);
                        //updateFlowApper1.setFlow_approver(_vplCreateUser);
                        //tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper1);

                        TbFlowProcessDetail updateFlowApper2 = new TbFlowProcessDetail();
                        updateFlowApper2.setUpdate_time(new Date());
                        updateFlowApper2.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper2.setFlow_no(_flow_no);
                        updateFlowApper2.setFlow_level(3);
                        updateFlowApper2.setFlow_approver(_vplCreateUser);
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper2);

                        //如果是第一个节点的话,还要去更新一下主节点上面的当前审核人,其实不更新也行
                        TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                        tbFlowProcessMainDao.updateFlowProcessMainForAuthorize(UserHeaderHolder.getUserId(), _flow_no, _flow_level);

                        TbFlowProcessDetail updateFlowApper3 = new TbFlowProcessDetail();
                        updateFlowApper3.setUpdate_time(new Date());
                        updateFlowApper3.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper3.setFlow_no(_flow_no);
                        updateFlowApper3.setFlow_level(4);
                        updateFlowApper3.setFlow_approver(_designer);
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper3);

                        //第一个节点更新三张表
                        //TbFlowCompVplPdm
                        //TbFlowCompManufacturer
                        //TbFlowProcessDetail
                        String tempPkgNamePdm = "";
                        String tempCompCode = "";
                        JSONArray compVplPdms = jsonObject.getJSONArray("compVplPdm");
                        for (int i = 0; i < compVplPdms.size(); i++) {
                            JSONObject compVplPdm = compVplPdms.getJSONObject(i);
                            TbFlowCompVplPdm tbFlowCompVplPdm = new TbFlowCompVplPdm();

                            Integer _id = compVplPdm.getInteger("id");
                            tbFlowCompVplPdm.setId(_id);
                            tempPkgNamePdm = compVplPdm.getString("S1PCBENCPFILENAME");
                            tempCompCode = compVplPdm.getString("s1partnumber");
                            tbFlowCompVplPdm.setPriority(compVplPdm.getString("priority"));

                            if (_id != null) {
                                tbFlowCompVplPdmDao.updateTbFlowCompVplPdm(tbFlowCompVplPdm);
                            }
                        }
                        JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");

                        if (handleVpl.equals("Y")) {
                            for (int i = 0; i < compManufacturers.size(); i++) {
                                JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                                TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();

                                Integer _id = compManufacturer.getInteger("id");
                                tbFlowCompManufacturer.setId(_id);
                                tbFlowCompManufacturer.setUpdate_time(new Date());
                                tbFlowCompManufacturer.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                                tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));
                                tbFlowCompManufacturer.setComp_code(tempCompCode);

                                //tbFlowCompManufacturer.setComp_resource(compManufacturer.getString("comp_resource"));
                                Object comp_resourceType = compManufacturer.get("comp_resource");
                                if (comp_resourceType instanceof JSONArray) {
                                    JSONArray comp_resource_filesArray = compManufacturer.getJSONArray("comp_resource") == null ? null : compManufacturer.getJSONArray("comp_resource");

                                    if (comp_resource_filesArray != null) {
                                        List<String> keyList = new ArrayList<>();

                                        for (int j = 0; j < comp_resource_filesArray.size(); j++) {
                                            JSONObject comp_resource_files = comp_resource_filesArray.getJSONObject(j);

                                            String _param_key = String.valueOf(UUID.randomUUID());

                                            keyList.add(_param_key);
                                            //tbFlowCompManufacturer.setComp_resource(_param_key);
                                            //updateParam.setVpl_model_excel(_param_key);

                                            TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                            tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                            tbKnowledgeBaseFile.setFlow_level(1);
                                            tbKnowledgeBaseFile.setParam_key(_param_key);

                                            String filename = comp_resource_files.get("file_name") == null ? null : comp_resource_files.get("file_name").toString();
                                            tbKnowledgeBaseFile.setFile_name(filename);
                                            tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                            tbKnowledgeBaseFile.setFile_relate_path(comp_resource_files.get("picRelatePath") == null ? null : comp_resource_files.get("picRelatePath").toString());
                                            tbKnowledgeBaseFile.setFile_type(3);
                                            tbKnowledgeBaseFile.setSecret_key(comp_resource_files.get("secretKey") == null ? null : comp_resource_files.get("secretKey").toString());
                                            tbKnowledgeBaseFile.setFile_sid(comp_resource_files.get("fileSid") == null ? null : comp_resource_files.get("fileSid").toString());

                                            List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                            tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                            tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                        }

                                        if (keyList != null && keyList.size() > 0) {
                                            tbFlowCompManufacturer.setComp_resource(String.join(",", keyList));
                                        }


                                    }
                                }

                                if (_id != null) {
                                    if (_id == 0) {
                                        tbFlowCompManufacturer.setFlow_no(_flow_no);
                                        tbFlowCompManufacturer.setFlow_level(1);

                                        List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                        tbFlowCompManufacturerList.add(tbFlowCompManufacturer);

                                        tbFlowCompManufacturerDao.insertTbFlowCompManufacturerBatch(tbFlowCompManufacturerList);
                                    } else {
                                        tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                                    }
                                }
                                //tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                            }

                            String other_resource = flow_info.getString("other_resource");
                            String cc = flow_info.getString("cc");

                            Object other_resource_filesType = flow_info.get("other_resource_files");
                            if (other_resource_filesType instanceof JSONArray) {
                                JSONArray other_resource_filesArray = flow_info.getJSONArray("other_resource_files") == null ? null : flow_info.getJSONArray("other_resource_files");
                                if (other_resource_filesArray != null) {
                                    List<String> keyList = new ArrayList<>();

                                    for (int i = 0; i < other_resource_filesArray.size(); i++) {

                                        JSONObject other_resource_files = other_resource_filesArray.getJSONObject(i);

                                        String _param_key = String.valueOf(UUID.randomUUID());
                                        keyList.add(_param_key);
                                        //updateParam.setOther_resource_files(_param_key);
                                        //updateParam.setVpl_model_excel(_param_key);
                                        TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                        tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                        tbKnowledgeBaseFile.setFlow_level(1);
                                        tbKnowledgeBaseFile.setParam_key(_param_key);

                                        String filename = other_resource_files.get("file_name") == null ? null : other_resource_files.get("file_name").toString();
                                        tbKnowledgeBaseFile.setFile_name(filename);
                                        tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                        tbKnowledgeBaseFile.setFile_relate_path(other_resource_files.get("picRelatePath") == null ? null : other_resource_files.get("picRelatePath").toString());
                                        tbKnowledgeBaseFile.setFile_type(3);
                                        tbKnowledgeBaseFile.setSecret_key(other_resource_files.get("secretKey") == null ? null : other_resource_files.get("secretKey").toString());
                                        tbKnowledgeBaseFile.setFile_sid(other_resource_files.get("fileSid") == null ? null : other_resource_files.get("fileSid").toString());

                                        List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                        tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                        tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                    }

                                    if (keyList != null && keyList.size() > 0) {
                                        updateParam.setOther_resource_files(String.join(",", keyList));
                                    }

                                }
                            }

                            updateParam.setOther_resource(other_resource);
                            updateParam.setCc(cc);
                        }


                        //List<Mpackage> listMpackage = mpackageDao.getMpackageByPkgName(tempPkgNamePdm);
                        List<vVplPackage> vVplPackageList = _vVplPackageDao.getvVplPackage(tempPkgNamePdm);
                        if (vVplPackageList != null && vVplPackageList.size() > 0) {
                            //有数据的话就直接带到流程里面去
                            //Mpackage mpackage = listMpackage.get(0);
                            vVplPackage mpackage = vVplPackageList.get(0);

                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                            tbFlowCompPkg.setFlow_no(_flow_no);
                            tbFlowCompPkg.setFlow_level(3);
                            tbFlowCompPkg.setCreate_time(new Date());
                            tbFlowCompPkg.setCreate_user(UserHeaderHolder.getUserId());
                            tbFlowCompPkg.setPkg_name(tempPkgNamePdm);

                            tbFlowCompPkg.setAssembly_type(mpackage.getAssembly_type());
                            tbFlowCompPkg.setFoot_num(mpackage.getFoot_num());
                            //tbFlowCompPkg.setIs_orientation(mpackage.getIs_orientation());
                            tbFlowCompPkg.setBody_length(mpackage.getBody_length());
                            tbFlowCompPkg.setBody_width(mpackage.getBody_width());
                            tbFlowCompPkg.setPad_airgap_min(mpackage.getPad_airgap_min());
                            tbFlowCompPkg.setPitch_o2c_x(mpackage.getPitch_o2c_x());
                            tbFlowCompPkg.setPitch_o2c_y(mpackage.getPitch_o2c_y());
                            tbFlowCompPkg.setIs_size_not_fit(mpackage.getIs_size_not_fit());
                            tbFlowCompPkg.setIs_grid_design(mpackage.getIs_grid_design());
                            tbFlowCompPkg.setIs_twins_design(mpackage.getIs_twins_design());
                            tbFlowCompPkg.setIs_special_design(mpackage.getIs_special_design());
                            tbFlowCompPkg.setIs_window_open(mpackage.getIs_window_open());
                            tbFlowCompPkg.setIs_small_air_gap(mpackage.getIs_small_air_gap());
                            //tbFlowCompPkg.setIs_vpl_model_imported("是");
                            tbFlowCompPkg.setIs_pkg_imported("否");
                            tbFlowCompPkg.setIs_required_eda_lib("否");
                            tbFlowCompPkg.setIs_vpl_parameters_imported("是");

                            //List<TbFlowCompPkg> listTbFlowCompPkg = new ArrayList<>();
                            //listTbFlowCompPkg.add(tbFlowCompPkg);

                            tbFlowCompPkgDao.updateTbFlowCompPkgByFlowNo(tbFlowCompPkg);

                        } else {
                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                            tbFlowCompPkg.setFlow_no(_flow_no);
                            tbFlowCompPkg.setFlow_level(3);
                            tbFlowCompPkg.setCreate_time(new Date());
                            tbFlowCompPkg.setCreate_user(UserHeaderHolder.getUserId());
                            tbFlowCompPkg.setPkg_name(tempPkgNamePdm);
                            //tbFlowCompPkg.setIs_vpl_model_imported("是");
                            tbFlowCompPkg.setIs_pkg_imported("是");
                            tbFlowCompPkg.setIs_required_eda_lib("是");
                            tbFlowCompPkg.setIs_vpl_parameters_imported("是");

                            tbFlowCompPkgDao.updateTbFlowCompPkgByFlowNo(tbFlowCompPkg);
                        }

                        //去查询模板中是否有0行的基本信息数据了,如果有那就找到对象
                        List<TbTaskTemplateData> codeAndPkg = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo2(_flow_no);
                        if (codeAndPkg != null && codeAndPkg.size() > 0) {
                            for (TbTaskTemplateData tbTaskTemplateData : codeAndPkg) {
                                if (tbTaskTemplateData.getParam_name() != null && tbTaskTemplateData.getParam_name().equals("器件编码")) {
                                    tbTaskTemplateDataDao.updateTaskTemplateDataValue(tempCompCode, tbTaskTemplateData.getId());
                                }
                                if (tbTaskTemplateData.getParam_name() != null && tbTaskTemplateData.getParam_name().equals("器件封装")) {
                                    tbTaskTemplateDataDao.updateTaskTemplateDataValue(tempPkgNamePdm, tbTaskTemplateData.getId());
                                }
                            }
                        } else {
                            //如果没有就插入
                            List<TbTaskTemplateData> codeAndPkgNew = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo3(_flow_no);
                            if (codeAndPkgNew != null && codeAndPkgNew.size() > 0) {
                                for (TbTaskTemplateData tbTaskTemplateData : codeAndPkgNew) {
                                    if (tbTaskTemplateData.getParam_name() != null && tbTaskTemplateData.getParam_name().equals("器件编码")) {
                                        tbTaskTemplateData.setParam_value(tempCompCode);
                                    }
                                    if (tbTaskTemplateData.getParam_name() != null && tbTaskTemplateData.getParam_name().equals("器件封装")) {
                                        tbTaskTemplateData.setParam_value(tempPkgNamePdm);
                                    }
                                    tbTaskTemplateData.setRow_sort(0); // 设置 row_sort 字段为 0
                                }
                                tbTaskTemplateDataDao.insertTaskTemplateDataBatch(codeAndPkgNew);
                            }
                        }

                    }

                    if (_flow_level == 2) {

                        //处理厂家信息
                        JSONArray compManufacturer = jsonObject.getJSONArray("compManufacturer");

                        Object vpl_attr_excelType = jsonObject.get("vpl_attr_excel");
                        if (vpl_attr_excelType instanceof JSONObject) {
                            //处理两个文件列表的对象信息
                            JSONObject vpl_attr_excel = jsonObject.getJSONObject("vpl_attr_excel");
                            if (vpl_attr_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_attr_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_attr_excel.get("fileName") == null ? null : vpl_attr_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_attr_excel.get("picRelatePath") == null ? null : vpl_attr_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_attr_excel.get("secretKey") == null ? null : vpl_attr_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_attr_excel.get("fileSid") == null ? null : vpl_attr_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }

                        Object vpl_model_excelType = jsonObject.get("vpl_model_excel");
                        if (vpl_model_excelType instanceof JSONObject) {
                            JSONObject vpl_model_excel = jsonObject.getJSONObject("vpl_model_excel");
                            if (vpl_model_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_model_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_model_excel.get("fileName") == null ? null : vpl_model_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_model_excel.get("picRelatePath") == null ? null : vpl_model_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_model_excel.get("secretKey") == null ? null : vpl_model_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_model_excel.get("fileSid") == null ? null : vpl_model_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }

                        String max_Body_height = flow_info.getString("max_Body_height");
                        String max_Pin_length = flow_info.getString("max_Pin_length");
                        String min_Pin_length = flow_info.getString("min_Pin_length");

                        updateParam.setMax_Body_height(max_Body_height);
                        updateParam.setMax_Pin_length(max_Pin_length);
                        updateParam.setMin_Pin_length(min_Pin_length);


                        //定义两个变量
                        //装联方式以及是否有极性
                        String tempAssembly_type = null;
                        String tempIsOrientation = null;
                        String tempPin_min_pitch = null;
                        double minPinMinPitch = Double.MAX_VALUE;
                        //修改两个属性数据
                        JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");

                        for (int i = 0; i < compVplAttrs.size(); i++) {
                            JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                            if (i == 0) {
                                tempAssembly_type = compVplAttr.getString("assembly_type");
                                tempIsOrientation = compVplAttr.getString("is_orientation");
                            }

                            TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();
                            tbFlowCompVplAttr.setId(compVplAttr.getInteger("id"));
                            tbFlowCompVplAttr.setUpdate_time(new Date());
                            tbFlowCompVplAttr.setUpdate_user(UserHeaderHolder.getUserId());

                            String manufacturer_type = compVplAttr.getString("manufacturer_type");
                            tbFlowCompVplAttr.setManufacturer_type(manufacturer_type);

                            tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                            tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                            tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));

                            String coplanarity = compVplAttr.getString("coplanarity");
                            tbFlowCompVplAttr.setCoplanarity(coplanarity);

                            String weight = compVplAttr.getString("weight");
                            tbFlowCompVplAttr.setWeight(weight);

                            tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                            tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                            tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                            tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                            tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                            tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                            tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                            tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                            tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                            tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));

                            String standoff = compVplAttr.getString("standoff");
                            tbFlowCompVplAttr.setStandoff(standoff);

                            tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                            tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                            tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                            tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                            tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                            tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                            tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                            tbFlowCompVplAttrDao.updateTbFlowCompVplAttr(tbFlowCompVplAttr);

                            if (compManufacturer != null) {
                                for (int j = 0; j < compManufacturer.size(); j++) {
                                    JSONObject compManufacturerJson = compManufacturer.getJSONObject(j);
                                    String tempManufacturer_type = compManufacturerJson.getString("manufacturer_type");
                                    if (tempManufacturer_type != null && manufacturer_type != null) {
                                        if (tempManufacturer_type.toLowerCase().equals(manufacturer_type.toLowerCase())) {
                                            TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                                            tbFlowCompManufacturer.setCoplanarity(coplanarity);
                                            tbFlowCompManufacturer.setStandoff(standoff);
                                            tbFlowCompManufacturer.setFlow_no(_flow_no);
                                            tbFlowCompManufacturer.setFlow_level(1);
                                            tbFlowCompManufacturer.setWeight(weight);

                                            tbFlowCompManufacturerDao.updateTbFlowCompManufacturer2(tbFlowCompManufacturer);
                                        }
                                    }
                                }
                            }

                        }

                        JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                        for (int i = 0; i < compVplPinAttrs.size(); i++) {
                            JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);

                            TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();

                            tbFlowCompVplPinAttr.setId(compVplPinAttr.getInteger("id"));
                            tbFlowCompVplPinAttr.setUpdate_time(new Date());
                            tbFlowCompVplPinAttr.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                            tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                            tempPin_min_pitch = compVplPinAttr.getString("pin_min_pitch");
                            // 将 pin_min_pitch 转换为 Double 并与当前最小值比较
                            try {
                                double pinMinPitch = Double.parseDouble(tempPin_min_pitch);
                                if (pinMinPitch < minPinMinPitch) {
                                    minPinMinPitch = pinMinPitch;
                                }
                            } catch (NumberFormatException e) {
                            }

                            tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                            tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                            tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                            tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                            tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                            tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                            tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                            tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                            tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                            tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                            tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                            tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                            tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                            tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                            tbFlowCompVplPinAttrDao.updateTbFlowCompVplPinAttr(tbFlowCompVplPinAttr);
                        }
                        if (minPinMinPitch != Double.MAX_VALUE) {
                            tempPin_min_pitch = String.valueOf(minPinMinPitch);
                        }

                        //修改流程节点的数据
                        String difficulty = flow_info.getString("difficulty");
                        String equivalent_num = flow_info.getString("equivalent_num");
                        String supply_vpl_create_user = flow_info.getString("supply_vpl_create_user");

                        updateParam.setSupply_vpl_create_user(supply_vpl_create_user);
                        updateParam.setDifficulty(difficulty);
                        updateParam.setEquivalent_num(equivalent_num);

                        //tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam);

                        //在第二个节点的时候,需要
                        TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                        tbFlowCompVpl.setFlow_no(_flow_no);
                        tbFlowCompVpl.setFlow_level(4);
                        tbFlowCompVpl.setUpdate_user(UserHeaderHolder.getUserId());
                        tbFlowCompVpl.setUpdate_time(new Date());
                        tbFlowCompVpl.setComponent_high_max_vpl(max_Body_height);
                        tbFlowCompVpl.setPin_high_max(max_Pin_length);
                        tbFlowCompVpl.setPin_high_min(min_Pin_length);
                        tbFlowCompVpl.setPin_min_pitch(tempPin_min_pitch);

                        tbFlowCompVplDao.updateTbFlowCompVplByFlowNo(tbFlowCompVpl);

                        TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                        tbFlowCompPkg.setFlow_no(_flow_no);
                        tbFlowCompPkg.setFlow_level(3);
                        tbFlowCompPkg.setCreate_time(new Date());
                        tbFlowCompPkg.setCreate_user(UserHeaderHolder.getUserId());
                        tbFlowCompPkg.setAssembly_type(tempAssembly_type);
                        tbFlowCompPkg.setIs_orientation(tempIsOrientation);

                        tbFlowCompPkgDao.updateTbFlowCompPkgByFlowNo(tbFlowCompPkg);
                    }

                    if (_flow_level == 3) {
                        String tempCompVpl = null;
                        //要获取一下当前的器件编码信息
                        JSONArray compVpl = jsonObject.getJSONArray("compVpl");
                        if (compVpl != null && compVpl.size() > 0) {
                            JSONObject _compVpl = compVpl.getJSONObject(0);

                            if (_compVpl != null) {
                                tempCompVpl = _compVpl.getString("comp_code");
                            }
                        }

                        if (tempCompVpl == null || tempCompVpl.isEmpty()) {
                            throw new Exception("器件料号为空,请刷新页面");
                            //return  ResultUtil.error(500,"器件料号为空,请刷新页面","","");
                        }

                        Object vpl_pkg_excelType = jsonObject.get("vpl_pkg_excel");
                        if (vpl_pkg_excelType instanceof JSONObject) {
                            //处理两个文件列表的对象信息
                            JSONObject vpl_pkg_excel = jsonObject.getJSONObject("vpl_pkg_excel");
                            if (vpl_pkg_excel != null) {
                                String _param_key = String.valueOf(UUID.randomUUID());

                                updateParam.setVpl_pkg_excel(_param_key);

                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                tbKnowledgeBaseFile.setFlow_level(_flow_level);
                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                String filename = vpl_pkg_excel.get("fileName") == null ? null : vpl_pkg_excel.get("fileName").toString();
                                tbKnowledgeBaseFile.setFile_name(filename);
                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                tbKnowledgeBaseFile.setFile_relate_path(vpl_pkg_excel.get("picRelatePath") == null ? null : vpl_pkg_excel.get("picRelatePath").toString());
                                tbKnowledgeBaseFile.setFile_type(3);
                                tbKnowledgeBaseFile.setSecret_key(vpl_pkg_excel.get("secretKey") == null ? null : vpl_pkg_excel.get("secretKey").toString());
                                tbKnowledgeBaseFile.setFile_sid(vpl_pkg_excel.get("fileSid") == null ? null : vpl_pkg_excel.get("fileSid").toString());

                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                            }
                        }

                        String tempPkgName = null;
                        String tempAssembly_Type = null;
                        JSONArray compPkgs = jsonObject.getJSONArray("compPkg");

                        for (int i = 0; i < compPkgs.size(); i++) {
                            JSONObject compPkg = compPkgs.getJSONObject(i);
                            TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();

                            tbFlowCompPkg.setId(compPkg.getInteger("id"));
                            tempPkgName = compPkg.getString("pkg_name");
                            tbFlowCompPkg.setPkg_name(tempPkgName);
                            tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                            tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                            tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                            tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                            tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                            tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                            tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                            tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                            tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                            tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                            tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                            tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                            tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                            tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));

                            String is_vpl_model_imported = compPkg.getString("is_vpl_model_imported");
                            if (is_vpl_model_imported == null || is_vpl_model_imported.isEmpty()) {
                                throw new Exception("VPL模型是否导入不可以为空");
                                //return ResultUtil.error(500, "VPL模型是否导入不可以为空", "", null);
                            } else if (!is_vpl_model_imported.equals("是")) {
                                throw new Exception("VPL模型必须是是才能提交");
                            }

                            tbFlowCompPkg.setIs_vpl_model_imported(is_vpl_model_imported);

                            String is_vpl_parameters_imported = compPkg.getString("is_vpl_parameters_imported");
                            if (is_vpl_parameters_imported == null || is_vpl_parameters_imported.isEmpty()) {
                                throw new Exception("VPL参数是否导入不可以为空");
                                //return ResultUtil.error(500, "VPL参数是否导入不可以为空", "", null);
                            }
                            tbFlowCompPkg.setIs_vpl_parameters_imported(is_vpl_parameters_imported);

                            String is_pkg_imported = compPkg.getString("is_pkg_imported");
                            if (is_pkg_imported == null || is_pkg_imported.isEmpty()) {
                                throw new Exception("封装参数是否导入不可以为空");
                                //return ResultUtil.error(500, "封装参数是否导入不可以为空", "", null);
                            }
                            tbFlowCompPkg.setIs_pkg_imported(is_pkg_imported);

                            tbFlowCompPkg.setIs_required_eda_lib(compPkg.getString("is_required_eda_lib"));
                            tbFlowCompPkg.setIs_required_vpl_pkg(compPkg.getString("is_required_vpl_pkg"));
                            tbFlowCompPkg.setTimeliness(compPkg.getString("timeliness"));

                            String quality = compPkg.getString("quality");
                            if (quality == null || quality.isEmpty()) {
                                throw new Exception("质量不可以为空");
                                //return ResultUtil.error(500, "质量不可以为空", "", null);
                            }
                            tbFlowCompPkg.setQuality(quality);

                            tbFlowCompPkg.setOverall_evaluation(compPkg.getString("overall_evaluation"));
                            tbFlowCompPkg.setAttachment(compPkg.getString("attachment"));

                            tbFlowCompPkgDao.updateTbFlowCompPkg(tbFlowCompPkg);

                            if (i == 0) {
                                TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                tbFlowCompVpl.setFlow_no(_flow_no);
                                tbFlowCompVpl.setFlow_level(4);
                                tbFlowCompVpl.setUpdate_user(UserHeaderHolder.getUserId());
                                tbFlowCompVpl.setUpdate_time(new Date());

                                String assembly_type = compPkg.getString("assembly_type");
                                tbFlowCompVpl.setAssembly_type(assembly_type);
                                if (assembly_type != null) {
                                    if (assembly_type.equalsIgnoreCase("tht") && (tempCompVpl.startsWith("0801") || tempCompVpl.startsWith("0810"))) {
                                        tbFlowCompVpl.setIs_tht_capcitor("是");
                                    } else {
                                        tbFlowCompVpl.setIs_tht_capcitor("否");
                                    }
                                } else {
                                    tbFlowCompVpl.setIs_tht_capcitor("否");
                                }

                                String pkg_name = compPkg.getString("pkg_name");
                                tbFlowCompVpl.setPkg_name(pkg_name);
                                if (pkg_name != null) {
                                    if (pkg_name.equalsIgnoreCase("PW0302A1C8-H3C24")) {
                                        tbFlowCompVpl.setIs_tht_power("是");
                                    } else if (pkg_name.toLowerCase().startsWith("pw-")) {
                                        tbFlowCompVpl.setIs_tht_power("是");
                                    } else {
                                        tbFlowCompVpl.setIs_tht_power("否");
                                    }
                                } else {
                                    tbFlowCompVpl.setIs_tht_power("否");
                                }

                                tbFlowCompVplDao.updateTbFlowCompVplByFlowNo(tbFlowCompVpl);
                            }


                        }
                    }

                    if (_flow_level == 4) {
                        JSONArray compVpls = jsonObject.getJSONArray("compVpl");
                        if (compVpls != null) {
                            for (int i = 0; i < compVpls.size(); i++) {
                                JSONObject compVpl = compVpls.getJSONObject(i);

                                TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                tbFlowCompVpl.setUpdate_time(new Date());
                                tbFlowCompVpl.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVpl.setId(compVpl.getInteger("id"));
                                tbFlowCompVpl.setComp_code(compVpl.getString("comp_code"));
                                tbFlowCompVpl.setComp_type(compVpl.getString("comp_type"));
                                tbFlowCompVpl.setPkg_name(compVpl.getString("pkg_name"));
                                tbFlowCompVpl.setAssembly_type(compVpl.getString("assembly_type"));
                                tbFlowCompVpl.setComponent_high_max_vpl(compVpl.getString("component_high_max_vpl"));
                                tbFlowCompVpl.setComponent_high_max_pdm(compVpl.getString("component_high_max_pdm"));
                                tbFlowCompVpl.setIs_dense_comp(compVpl.getString("is_dense_comp"));
                                tbFlowCompVpl.setStress_properties(compVpl.getString("stress_properties"));
                                tbFlowCompVpl.setPin_high_max(compVpl.getString("pin_high_max"));
                                tbFlowCompVpl.setPin_high_min(compVpl.getString("pin_high_min"));
                                tbFlowCompVpl.setPastemask_thickness_max(compVpl.getString("pastemask_thickness_max"));
                                tbFlowCompVpl.setPastemask_thickness_min(compVpl.getString("pastemask_thickness_min"));
                                tbFlowCompVpl.setPth_diameter_min(compVpl.getString("pth_diameter_min"));
                                tbFlowCompVpl.setPin_min_pitch(compVpl.getString("pin_min_pitch"));
                                tbFlowCompVpl.setIs_tht_power(compVpl.getString("is_tht_power"));
                                tbFlowCompVpl.setIs_tht_capcitor(compVpl.getString("is_tht_capcitor"));
                                tbFlowCompVpl.setIs_glue(compVpl.getString("is_glue"));
                                tbFlowCompVpl.setIs_little_retentionforce(compVpl.getString("is_little_retentionforce"));

                                tbFlowCompVplDao.updateTbFlowCompVpl(tbFlowCompVpl);
                            }
                        }

                        JSONArray compPkgs = jsonObject.getJSONArray("compPkg");
                        if (compPkgs != null) {
                            for (int i = 0; i < compPkgs.size(); i++) {
                                JSONObject compPkg = compPkgs.getJSONObject(i);

                                TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                                tbFlowCompPkg.setUpdate_time(new Date());
                                tbFlowCompPkg.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompPkg.setId(compPkg.getInteger("id"));
                                tbFlowCompPkg.setPkg_name(compPkg.getString("pkg_name"));
                                tbFlowCompPkg.setAssembly_type(compPkg.getString("assembly_type"));
                                tbFlowCompPkg.setFoot_num(compPkg.getString("foot_num"));
                                tbFlowCompPkg.setIs_orientation(compPkg.getString("is_orientation"));
                                tbFlowCompPkg.setBody_length(compPkg.getString("body_length"));
                                tbFlowCompPkg.setBody_width(compPkg.getString("body_width"));
                                tbFlowCompPkg.setPad_airgap_min(compPkg.getString("pad_airgap_min"));
                                tbFlowCompPkg.setPitch_o2c_x(compPkg.getString("pitch_o2c_x"));
                                tbFlowCompPkg.setPitch_o2c_y(compPkg.getString("pitch_o2c_y"));
                                tbFlowCompPkg.setIs_size_not_fit(compPkg.getString("is_size_not_fit"));
                                tbFlowCompPkg.setIs_grid_design(compPkg.getString("is_grid_design"));
                                tbFlowCompPkg.setIs_twins_design(compPkg.getString("is_twins_design"));
                                tbFlowCompPkg.setIs_special_design(compPkg.getString("is_special_design"));
                                tbFlowCompPkg.setIs_window_open(compPkg.getString("is_window_open"));
                                tbFlowCompPkg.setIs_small_air_gap(compPkg.getString("is_small_air_gap"));

                                tbFlowCompPkgDao.updateTbFlowCompPkg(tbFlowCompPkg);
                            }
                        }

                        JSONArray compManufacturers = jsonObject.getJSONArray("compManufacturer");
                        if (compManufacturers != null) {
                            for (int i = 0; i < compManufacturers.size(); i++) {
                                JSONObject compManufacturer = compManufacturers.getJSONObject(i);
                                TbFlowCompManufacturer tbFlowCompManufacturer = new TbFlowCompManufacturer();
                                tbFlowCompManufacturer.setUpdate_time(new Date());
                                tbFlowCompManufacturer.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompManufacturer.setId(compManufacturer.getInteger("id"));
                                tbFlowCompManufacturer.setManufacturer(compManufacturer.getString("manufacturer"));
                                tbFlowCompManufacturer.setManufacturer_type(compManufacturer.getString("manufacturer_type"));
                                tbFlowCompManufacturer.setWeight(compManufacturer.getString("weight"));
                                tbFlowCompManufacturer.setCoplanarity(compManufacturer.getString("coplanarity"));
                                tbFlowCompManufacturer.setStandoff(compManufacturer.getString("standoff"));
                                tbFlowCompManufacturer.setSolder_tg_max(compManufacturer.getString("solder_tg_max"));
                                tbFlowCompManufacturer.setBga_height_min(compManufacturer.getString("bga_height_min"));
                                tbFlowCompManufacturer.setUnbd_thickness_min(compManufacturer.getString("unbd_thickness_min"));
                                tbFlowCompManufacturer.setBoard_thickness_min(compManufacturer.getString("board_thickness_min"));
                                tbFlowCompManufacturer.setBoard_thickness_max(compManufacturer.getString("board_thickness_max"));
                                tbFlowCompManufacturer.setIs_secd_reflow_drop(compManufacturer.getString("is_secd_reflow_drop"));
                                tbFlowCompManufacturer.setThermal_contact_dimension(compManufacturer.getString("thermal_contact_dimension"));

                                tbFlowCompManufacturerDao.updateTbFlowCompManufacturer(tbFlowCompManufacturer);
                            }
                        }

                        JSONArray compVplAttrs = jsonObject.getJSONArray("compVplAttr");
                        if (compVplAttrs != null) {
                            for (int i = 0; i < compVplAttrs.size(); i++) {
                                JSONObject compVplAttr = compVplAttrs.getJSONObject(i);

                                TbFlowCompVplAttr tbFlowCompVplAttr = new TbFlowCompVplAttr();
                                tbFlowCompVplAttr.setUpdate_time(new Date());
                                tbFlowCompVplAttr.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVplAttr.setId(compVplAttr.getInteger("id"));
                                tbFlowCompVplAttr.setManufacturer_type(compVplAttr.getString("manufacturer_type"));
                                tbFlowCompVplAttr.setMpn(compVplAttr.getString("mpn"));
                                tbFlowCompVplAttr.setMcode(compVplAttr.getString("mcode"));
                                tbFlowCompVplAttr.setPkg_name(compVplAttr.getString("pkg_name"));
                                tbFlowCompVplAttr.setCoplanarity(compVplAttr.getString("coplanarity"));
                                tbFlowCompVplAttr.setWeight(compVplAttr.getString("weight"));
                                tbFlowCompVplAttr.setAssembly_type(compVplAttr.getString("assembly_type"));
                                tbFlowCompVplAttr.setBody_length(compVplAttr.getString("body_length"));
                                tbFlowCompVplAttr.setBody_width(compVplAttr.getString("body_width"));
                                tbFlowCompVplAttr.setBody_height(compVplAttr.getString("body_height"));
                                tbFlowCompVplAttr.setBody_length_tol_p(compVplAttr.getString("body_length_tol_p"));
                                tbFlowCompVplAttr.setBody_length_tol_n(compVplAttr.getString("body_length_tol_n"));
                                tbFlowCompVplAttr.setBody_width_tol_p(compVplAttr.getString("body_width_tol_p"));
                                tbFlowCompVplAttr.setBody_width_tol_n(compVplAttr.getString("body_width_tol_n"));
                                tbFlowCompVplAttr.setBody_height_tol_p(compVplAttr.getString("body_height_tol_p"));
                                tbFlowCompVplAttr.setBody_height_tol_n(compVplAttr.getString("body_height_tol_n"));
                                tbFlowCompVplAttr.setStandoff(compVplAttr.getString("standoff"));
                                tbFlowCompVplAttr.setPth_diameter_min(compVplAttr.getString("pth_diameter_min"));
                                tbFlowCompVplAttr.setVpl_creater(compVplAttr.getString("vpl_creater"));
                                tbFlowCompVplAttr.setApprover(compVplAttr.getString("approver"));
                                tbFlowCompVplAttr.setRemark(compVplAttr.getString("remark"));
                                tbFlowCompVplAttr.setIs_orientation(compVplAttr.getString("is_orientation"));
                                tbFlowCompVplAttr.setIs_high_step(compVplAttr.getString("is_high_step"));
                                tbFlowCompVplAttr.setNumber(compVplAttr.getString("number"));

                                tbFlowCompVplAttrDao.updateTbFlowCompVplAttr(tbFlowCompVplAttr);
                            }
                        }

                        JSONArray compVplPinAttrs = jsonObject.getJSONArray("compVplPinAttr");
                        if (compVplPinAttrs != null) {
                            for (int i = 0; i < compVplPinAttrs.size(); i++) {
                                JSONObject compVplPinAttr = compVplPinAttrs.getJSONObject(i);
                                TbFlowCompVplPinAttr tbFlowCompVplPinAttr = new TbFlowCompVplPinAttr();
                                tbFlowCompVplPinAttr.setUpdate_time(new Date());
                                tbFlowCompVplPinAttr.setUpdate_user(UserHeaderHolder.getUserId());

                                tbFlowCompVplPinAttr.setId(compVplPinAttr.getInteger("id"));
                                tbFlowCompVplPinAttr.setMpn(compVplPinAttr.getString("mpn"));
                                tbFlowCompVplPinAttr.setPkg_name(compVplPinAttr.getString("pkg_name"));
                                tbFlowCompVplPinAttr.setPin_min_pitch(compVplPinAttr.getString("pin_min_pitch"));
                                tbFlowCompVplPinAttr.setPin_count(compVplPinAttr.getString("pin_count"));
                                tbFlowCompVplPinAttr.setPin_number(compVplPinAttr.getString("pin_number"));
                                tbFlowCompVplPinAttr.setPin_x_v(compVplPinAttr.getString("pin_x_v"));
                                tbFlowCompVplPinAttr.setPin_y_v(compVplPinAttr.getString("pin_y_v"));
                                tbFlowCompVplPinAttr.setPin_length(compVplPinAttr.getString("pin_length"));
                                tbFlowCompVplPinAttr.setPin_width(compVplPinAttr.getString("pin_width"));
                                tbFlowCompVplPinAttr.setPin_length_tol_p(compVplPinAttr.getString("pin_length_tol_p"));
                                tbFlowCompVplPinAttr.setPin_length_tol_n(compVplPinAttr.getString("pin_length_tol_n"));
                                tbFlowCompVplPinAttr.setPin_width_tol_p(compVplPinAttr.getString("pin_width_tol_p"));
                                tbFlowCompVplPinAttr.setPin_width_tol_n(compVplPinAttr.getString("pin_width_tol_n"));
                                tbFlowCompVplPinAttr.setPin_type(compVplPinAttr.getString("pin_type"));
                                tbFlowCompVplPinAttr.setPin_high(compVplPinAttr.getString("pin_high"));
                                tbFlowCompVplPinAttr.setPin_high_tol_p(compVplPinAttr.getString("pin_high_tol_p"));
                                tbFlowCompVplPinAttr.setPin_high_tol_n(compVplPinAttr.getString("pin_high_tol_n"));

                                tbFlowCompVplPinAttrDao.updateTbFlowCompVplPinAttr(tbFlowCompVplPinAttr);
                            }
                        }

                        if (_is_vpl_parameters_checked == null || !_is_vpl_parameters_checked.equals("是")) {
                            throw new Exception("VPL参数检查是否正确必须是是才能提交审核");
                            //return ResultUtil.error(500, "VPL参数检查是否正确必须是是才能提交审核", "", null);
                        }

                    }
                }

                newData = handleApproveFlow(_flow_no, _comments, is_need_knowledge_base);
                /**
                 //2、再处理审批的主表明细表数据
                 TbFlowProcessMain param = new TbFlowProcessMain();
                 param.setFlow_no(_flow_no);

                 List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMain(param);
                 if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                 TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);

                 Integer _flow_status = tbFlowProcessMain.getStatus();
                 //1 待审核 2审核中 3审核完成 4草稿
                 if (_flow_status == 3) {
                 return ResultUtil.error(500, "该流程已审核完成", "", null);
                 } else {
                 //获取当前所在节点
                 String _flow_type = tbFlowProcessMain.getFlow_type();
                 Integer _now_level = tbFlowProcessMain.getNow_level();

                 //去查询是否有下一个节点,正常是不会为空的,为空就说明就成结束了.但是加上个非空判断吧
                 if (_now_level != null) {
                 //获取流程明细去,看看有没有下一步流程,没有下一步流程就更新主表到审核完成,如果有就把下一节点,审批人更新到主表上
                 TbFlowProcessDetail param2 = new TbFlowProcessDetail();
                 param2.setFlow_no(_flow_no);
                 param2.setFlow_type(_flow_type);
                 param2.setFlow_level((_now_level + 1));

                 List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
                 if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                 TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                 //更新主表信息
                 TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                 tempFlowProcessMain.setFlow_no(_flow_no);
                 tempFlowProcessMain.setNow_level(tbFlowProcessDetail.getFlow_level());
                 tempFlowProcessMain.setNow_approver(tbFlowProcessDetail.getFlow_approver());
                 tempFlowProcessMain.setStatus(2);//审核中
                 tempFlowProcessMain.setUpdate_time(new Date());
                 tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                 tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                 //更新明细表的信息
                 TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                 tempFlowProcessDetail.setFlow_no(_flow_no);
                 tempFlowProcessDetail.setFlow_level(_now_level);
                 tempFlowProcessDetail.setStatus(2);
                 tempFlowProcessDetail.setUpdate_time(new Date());
                 tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                 tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail);

                 //写入审核记录表
                 TbFlowProcessDetail param3 = new TbFlowProcessDetail();
                 param3.setFlow_no(_flow_no);
                 param3.setFlow_type(_flow_type);
                 param3.setFlow_level(_now_level);
                 List<TbFlowProcessDetail> tbFlowProcessDetailList2 = tbFlowProcessDetailDao.getFlowProcessDetail(param3);
                 TbFlowProcessDetail temp = tbFlowProcessDetailList2.get(0);

                 TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                 tbFlowProcessRecords.setFlow_no(_flow_no);
                 tbFlowProcessRecords.setFlow_type(_flow_type);
                 tbFlowProcessRecords.setFlow_name(temp.getFlow_name());
                 tbFlowProcessRecords.setFlow_level(_now_level);
                 tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                 tbFlowProcessRecords.setResult("审核通过");
                 //tbFlowProcessRecords.setRemark(_remark);
                 tbFlowProcessRecords.setCreate_time(new Date());
                 tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                 tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                 //更新版本表
                 TbTaskVersion taskVersion = new TbTaskVersion();
                 taskVersion.setFlow_no(_flow_no);
                 taskVersion.setStatus(2);
                 tbTaskVersionDao.updateTaskVersionStatus(taskVersion);
                 } else {
                 //更新主表信息
                 TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                 tempFlowProcessMain.setFlow_no(_flow_no);
                 tempFlowProcessMain.setNow_level(0);
                 tempFlowProcessMain.setNow_approver("");
                 tempFlowProcessMain.setStatus(3);
                 tempFlowProcessMain.setUpdate_time(new Date());
                 tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                 tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                 //更新明细表的信息
                 TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                 tempFlowProcessDetail.setFlow_no(_flow_no);
                 tempFlowProcessDetail.setFlow_level(_now_level);
                 tempFlowProcessDetail.setStatus(2);
                 tempFlowProcessDetail.setComments(_comments);
                 //tempFlowProcessDetail.setRemark(_remark);
                 tempFlowProcessDetail.setUpdate_time(new Date());
                 tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                 tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail);

                 //写入审核记录表
                 TbFlowProcessDetail param3 = new TbFlowProcessDetail();
                 param3.setFlow_no(_flow_no);
                 param3.setFlow_type(_flow_type);
                 param3.setFlow_level(_now_level);
                 List<TbFlowProcessDetail> tbFlowProcessDetailList2 = tbFlowProcessDetailDao.getFlowProcessDetail(param3);
                 TbFlowProcessDetail temp = tbFlowProcessDetailList2.get(0);

                 TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                 tbFlowProcessRecords.setFlow_no(_flow_no);
                 tbFlowProcessRecords.setFlow_type(_flow_type);
                 tbFlowProcessRecords.setFlow_name(temp.getFlow_name());
                 tbFlowProcessRecords.setFlow_level(_now_level);
                 tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                 tbFlowProcessRecords.setResult("审核完成");
                 tbFlowProcessRecords.setRemark(_comments);
                 tbFlowProcessRecords.setCreate_time(new Date());
                 tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                 tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                 //更新版本表
                 TbTaskVersion taskVersion = new TbTaskVersion();
                 taskVersion.setFlow_no(_flow_no);
                 taskVersion.setStatus(3);
                 tbTaskVersionDao.updateTaskVersionStatus(taskVersion);
                 }
                 } else {
                 return ResultUtil.error(500, "该流程已审核完成", "", null);
                 }
                 }
                 } else {
                 return ResultUtil.error(500, "未查询到该流程", "", null);
                 }
                 */

                if (is_send_mail) {
                    sendMail(flow_type, _flow_no, _flow_level);
                }
            }


            if (is_need_model) {
                //处理好数据以后就是更新数据
                resultList.forEach(entity -> {
                    Integer tempRowSort = entity.getRow_sort();

                    if (tempRowSort != null && tempRowSort != -1) {
                        Integer tempIsAdd = entity.getIs_Add();
                        entity.setUpdate_time(new Date());
                        entity.setUpdate_user(UserHeaderHolder.getUserId());
                        if (tempIsAdd == null || entity.getIs_Add() == 1) {

                            tbTaskTemplateDataDao.updateTaskTemplateData(entity);
                        }

                        if (tempIsAdd != null && entity.getIs_Add() == 0) {
                            List<TbTaskTemplateData> listAdd = new ArrayList<>();
                            entity.setCreate_time(new Date());
                            entity.setCreate_user(UserHeaderHolder.getUserId());
                            listAdd.add(entity);

                            tbTaskTemplateDataDao.insertTaskTemplateDataBatch(listAdd);
                        }
                    }
                });
            }

            tbFlowProcessDetailDao.updateFlowProcessDetail(updateParam);

            if (newData == null || newData.getCode() == null) {
                return ResultUtil.success(_flow_no);
            } else {
                if (newData.getData().equals(_flow_no)) {
                    return ResultUtil.success(_flow_no);
                } else {
                    return newData;
                }
            }

        } catch (Exception e) {
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //System.out.println(e.getMessage());
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    public Result handleUpdateFlow(String _flow_no, JSONObject jsonObject, String type, String flow_type) {
        //20250311附加逻辑,如果说传过来的编号已经审批完成了.那么就认为进入修改流程
        List<TbFlowProcessMain> listTbFlowProcessMain = tbFlowProcessMainDao.getFlowProcessMainByFlowNo(_flow_no);
        if ((flow_type.equals("design") || flow_type.equals("device") || flow_type.equals("vpl"))) {
            if (listTbFlowProcessMain != null && listTbFlowProcessMain.size() > 0) {
                TbFlowProcessMain tbFlowProcessMain = listTbFlowProcessMain.get(0);
                if (tbFlowProcessMain.getStatus() == 3) {
                    //已经审批完成,那么补一条更新日志,然后重置审批状态

                    //获取第一个节点的审核人信息
                    TbFlowProcessDetail tbFlowProcessDetailQuery = new TbFlowProcessDetail();
                    tbFlowProcessDetailQuery.setFlow_no(_flow_no);
                    tbFlowProcessDetailQuery.setFlow_type(flow_type);

                    if (flow_type.equals("vpl")) {
                        tbFlowProcessDetailQuery.setFlow_level(4);
                    } else {
                        tbFlowProcessDetailQuery.setFlow_level(1);
                    }

                    List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(tbFlowProcessDetailQuery);
                    if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                        TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);
                        //更新主表信息
                        TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                        tempFlowProcessMain.setFlow_no(_flow_no);
                        tempFlowProcessMain.setNow_level(tbFlowProcessDetail.getFlow_level());
                        tempFlowProcessMain.setNow_approver(tbFlowProcessDetail.getFlow_approver());
                        tempFlowProcessMain.setStatus(2);//审核中
                        tempFlowProcessMain.setUpdate_time(new Date());
                        tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                        tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                        //更新明细表的信息
                        TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                        tempFlowProcessDetail.setFlow_no(_flow_no);
                        if (flow_type.equals("vpl")) {
                            tempFlowProcessDetail.setFlow_level(4);
                        }
                        tempFlowProcessDetail.setStatus(1);
                        tempFlowProcessDetail.setUpdate_time(new Date());
                        tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                        tbFlowProcessDetailDao.updateFlowProcessDetail2(tempFlowProcessDetail);

                        TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                        tbFlowProcessRecords.setFlow_no(_flow_no);
                        tbFlowProcessRecords.setFlow_type(flow_type);
                        tbFlowProcessRecords.setFlow_level(1);
                        tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                        tbFlowProcessRecords.setResult("开始流程修改");
                        //tbFlowProcessRecords.setRemark(_remark);
                        tbFlowProcessRecords.setCreate_time(new Date());
                        tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                        tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                        //更新版本表
                        TbTaskVersion taskVersion = new TbTaskVersion();
                        taskVersion.setFlow_no(_flow_no);
                        taskVersion.setStatus(2);
                        tbTaskVersionDao.updateTaskVersionStatus(taskVersion);
                    }
                }
            }
        }

        //已经撤销的流程不允许再进行操作
        if (listTbFlowProcessMain != null && listTbFlowProcessMain.size() > 0) {
            TbFlowProcessMain tbFlowProcessMain = listTbFlowProcessMain.get(0);
            if (tbFlowProcessMain.getStatus() == 5) {
                return ResultUtil.error(500, "该流程已经撤销，不允许再进行操作", "", null);
            }
        }

        return ResultUtil.success(_flow_no);
    }

    @Transactional(transactionManager = "MysqlTransactionManager7")
    public Result handleApproveFlow(String _flow_no, String _comments, boolean is_need_knowledge_base) {
        try {
            //2、再处理审批的主表明细表数据
            TbFlowProcessMain param = new TbFlowProcessMain();
            param.setFlow_no(_flow_no);

            List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMain(param);
            if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                TbFlowProcessMain tbFlowProcessMain = tbFlowProcessMainList.get(0);

                Integer _flow_status = tbFlowProcessMain.getStatus();
                //1 待审核 2审核中 3审核完成 4草稿
                if (_flow_status == 3) {
                    return ResultUtil.error(500, "该流程已审核完成", "", null);
                } else {
                    //获取当前所在节点
                    String _flow_type = tbFlowProcessMain.getFlow_type();
                    Integer _now_level = tbFlowProcessMain.getNow_level();

                    //去查询是否有下一个节点,正常是不会为空的,为空就说明就成结束了.但是加上个非空判断吧
                    if (_now_level != null) {
                        Integer toLevel=_now_level + 1;
                        //20250918 修改逻辑 增加跳过节点,直接到指定节点
                        if(_flow_type!=null&&_flow_type.equals("vpl")&&_now_level==1)
                        {
                            //去获取一下第一个节点的信息过来.如果是需要的话就走正常流程,否则就是跳到4这个节点
                            TbFlowProcessDetail paramSkip = new TbFlowProcessDetail();
                            paramSkip.setFlow_no(_flow_no);
                            paramSkip.setFlow_type(_flow_type);
                            paramSkip.setFlow_level(1);
                            List<TbFlowProcessDetail> tbFlowProcessDetailSkip = tbFlowProcessDetailDao.getFlowProcessDetail(paramSkip);
                            if(tbFlowProcessDetailSkip!=null&&tbFlowProcessDetailSkip.size()>0)
                            {
                                TbFlowProcessDetail tempValue=tbFlowProcessDetailSkip.get(0);
                                
                                if(tempValue.getIs_skip()!=null&&tempValue.getIs_skip()==0)
                                {
                                    toLevel=4;
                                }
                            }
                        }

                        //获取流程明细去,看看有没有下一步流程,没有下一步流程就更新主表到审核完成,如果有就把下一节点,审批人更新到主表上
                        TbFlowProcessDetail param2 = new TbFlowProcessDetail();
                        param2.setFlow_no(_flow_no);
                        param2.setFlow_type(_flow_type);
                        param2.setFlow_level(toLevel);

                        List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
                        if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                            TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                            //更新主表信息
                            TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                            tempFlowProcessMain.setFlow_no(_flow_no);
                            tempFlowProcessMain.setNow_level(tbFlowProcessDetail.getFlow_level());
                            tempFlowProcessMain.setNow_approver(tbFlowProcessDetail.getFlow_approver());
                            tempFlowProcessMain.setStatus(2);//审核中
                            tempFlowProcessMain.setUpdate_time(new Date());
                            tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                            //更新明细表的信息
                            TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                            tempFlowProcessDetail.setFlow_no(_flow_no);
                            tempFlowProcessDetail.setFlow_level(_now_level);
                            tempFlowProcessDetail.setStatus(2);
                            tempFlowProcessDetail.setUpdate_time(new Date());
                            tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail);

                            //写入审核记录表
                            TbFlowProcessDetail param3 = new TbFlowProcessDetail();
                            param3.setFlow_no(_flow_no);
                            param3.setFlow_type(_flow_type);
                            param3.setFlow_level(_now_level);
                            List<TbFlowProcessDetail> tbFlowProcessDetailList2 = tbFlowProcessDetailDao.getFlowProcessDetail(param3);
                            TbFlowProcessDetail temp = tbFlowProcessDetailList2.get(0);

                            TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                            tbFlowProcessRecords.setFlow_no(_flow_no);
                            tbFlowProcessRecords.setFlow_type(_flow_type);
                            tbFlowProcessRecords.setFlow_name(temp.getFlow_name());
                            tbFlowProcessRecords.setFlow_level(_now_level);
                            tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                            tbFlowProcessRecords.setResult("审核通过");
                            tbFlowProcessRecords.setRemark(_comments);
                            tbFlowProcessRecords.setCreate_time(new Date());
                            tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                            tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                            //更新版本表
                            TbTaskVersion taskVersion = new TbTaskVersion();
                            taskVersion.setFlow_no(_flow_no);
                            taskVersion.setStatus(2);
                            tbTaskVersionDao.updateTaskVersionStatus(taskVersion);

                            return ResultUtil.success(_flow_no);
                        } else {
                            //更新主表信息
                            TbFlowProcessMain tempFlowProcessMain = new TbFlowProcessMain();
                            tempFlowProcessMain.setFlow_no(_flow_no);
                            tempFlowProcessMain.setNow_level(0);
                            tempFlowProcessMain.setNow_approver("");
                            tempFlowProcessMain.setStatus(3);
                            tempFlowProcessMain.setUpdate_time(new Date());
                            tempFlowProcessMain.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowProcessMainDao.updateFlowProcessMain(tempFlowProcessMain);

                            //更新明细表的信息
                            TbFlowProcessDetail tempFlowProcessDetail = new TbFlowProcessDetail();
                            tempFlowProcessDetail.setFlow_no(_flow_no);
                            tempFlowProcessDetail.setFlow_level(_now_level);
                            tempFlowProcessDetail.setStatus(2);
                            tempFlowProcessDetail.setComments(_comments);
                            //tempFlowProcessDetail.setRemark(_remark);
                            tempFlowProcessDetail.setUpdate_time(new Date());
                            tempFlowProcessDetail.setUpdate_user(UserHeaderHolder.getUserId());
                            tbFlowProcessDetailDao.updateFlowProcessDetail(tempFlowProcessDetail);

                            //写入审核记录表
                            TbFlowProcessDetail param3 = new TbFlowProcessDetail();
                            param3.setFlow_no(_flow_no);
                            param3.setFlow_type(_flow_type);
                            param3.setFlow_level(_now_level);
                            List<TbFlowProcessDetail> tbFlowProcessDetailList2 = tbFlowProcessDetailDao.getFlowProcessDetail(param3);
                            TbFlowProcessDetail temp = tbFlowProcessDetailList2.get(0);

                            TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                            tbFlowProcessRecords.setFlow_no(_flow_no);
                            tbFlowProcessRecords.setFlow_type(_flow_type);
                            tbFlowProcessRecords.setFlow_name(temp.getFlow_name());
                            tbFlowProcessRecords.setFlow_level(_now_level);
                            tbFlowProcessRecords.setFlow_approver(tbFlowProcessMain.getNow_approver());
                            tbFlowProcessRecords.setResult("审核完成");
                            tbFlowProcessRecords.setRemark(_comments);
                            tbFlowProcessRecords.setCreate_time(new Date());
                            tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());

                            tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                            //更新版本表
                            TbTaskVersion taskVersion = new TbTaskVersion();
                            taskVersion.setFlow_no(_flow_no);
                            taskVersion.setStatus(3);
                            tbTaskVersionDao.updateTaskVersionStatus(taskVersion);

                            //20250320 写入知识库表数据
                            if (is_need_knowledge_base) {
                                List<TbTaskTemplateData> tbTaskTemplateDataList = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(_flow_no);
                                if (tbTaskTemplateDataList != null && tbTaskTemplateDataList.size() > 0) {
                                    List<TbKnowledgeBaseData> tbKnowledgeBaseDataList = new ArrayList<>();

                                    // 遍历 TbTaskTemplateData 列表，并将每个元素转换为 TbKnowledgeBaseData
                                    for (TbTaskTemplateData tbTaskTemplateData : tbTaskTemplateDataList) {
                                        TbKnowledgeBaseData tbKnowledgeBaseData = new TbKnowledgeBaseData();
                                        // 将 TbTaskTemplateData 的字段值复制到 TbKnowledgeBaseData
                                        tbKnowledgeBaseData.setId(tbTaskTemplateData.getId());
                                        tbKnowledgeBaseData.setFlow_no(tbTaskTemplateData.getFlow_no());
                                        tbKnowledgeBaseData.setFlow_level(tbTaskTemplateData.getFlow_level());
                                        tbKnowledgeBaseData.setVersion(tbTaskTemplateData.getVersion());
                                        tbKnowledgeBaseData.setTemplate_type(tbTaskTemplateData.getTemplate_type());
                                        tbKnowledgeBaseData.setParent_id(tbTaskTemplateData.getParent_id());
                                        tbKnowledgeBaseData.setParam_name(tbTaskTemplateData.getParam_name());
                                        tbKnowledgeBaseData.setParam_name_en(tbTaskTemplateData.getParam_name_en());
                                        tbKnowledgeBaseData.setParam_key(tbTaskTemplateData.getParam_key());
                                        tbKnowledgeBaseData.setParam_type(tbTaskTemplateData.getParam_type());
                                        tbKnowledgeBaseData.setParam_value(tbTaskTemplateData.getParam_value());
                                        tbKnowledgeBaseData.setLevel(tbTaskTemplateData.getLevel());
                                        tbKnowledgeBaseData.setSelect_level(tbTaskTemplateData.getSelect_level());
                                        tbKnowledgeBaseData.setParent_select_id(tbTaskTemplateData.getParent_select_id());
                                        tbKnowledgeBaseData.setTip(tbTaskTemplateData.getTip());
                                        tbKnowledgeBaseData.setRemark(tbTaskTemplateData.getRemark());
                                        tbKnowledgeBaseData.setCreate_user(tbTaskTemplateData.getCreate_user());
                                        tbKnowledgeBaseData.setCreate_time(tbTaskTemplateData.getCreate_time());
                                        tbKnowledgeBaseData.setUpdate_user(tbTaskTemplateData.getUpdate_user());
                                        tbKnowledgeBaseData.setUpdate_time(tbTaskTemplateData.getUpdate_time());
                                        tbKnowledgeBaseData.setStatus(tbTaskTemplateData.getStatus());
                                        tbKnowledgeBaseData.setChildren(tbTaskTemplateData.getChildren());
                                        tbKnowledgeBaseData.setParent_param_key(tbTaskTemplateData.getParent_param_key());
                                        tbKnowledgeBaseData.setSort(tbTaskTemplateData.getSort());
                                        tbKnowledgeBaseData.setRow_sort(tbTaskTemplateData.getRow_sort());
                                        tbKnowledgeBaseData.setRow_sort_old(tbTaskTemplateData.getRow_sort_old());
                                        tbKnowledgeBaseData.setIs_Add(tbTaskTemplateData.getIs_Add());
                                        tbKnowledgeBaseData.setIs_value(tbTaskTemplateData.getIs_value());
                                        tbKnowledgeBaseData.setChildrenCount(tbTaskTemplateData.getChildrenCount());
                                        tbKnowledgeBaseData.setKnowledge_base_key(tbFlowProcessMain.getKnowledge_base_key());

                                        // 将转换后的 TbKnowledgeBaseData 添加到新的列表中
                                        tbKnowledgeBaseDataList.add(tbKnowledgeBaseData);
                                    }

                                    TbKnowledgeBaseData tbKnowledgeBaseData = new TbKnowledgeBaseData();
                                    tbKnowledgeBaseData.setKnowledge_base_key(tbFlowProcessMain.getKnowledge_base_key());
                                    //删除知识库的数据信息
                                    tbKnowledgeBaseDataDao.deleteTaskTemplateData(tbKnowledgeBaseData);
                                    tbKnowledgeBaseDataDao.insertTbKnowledgeBaseDataBatch(tbKnowledgeBaseDataList);
                                }
                            }

                            return ResultUtil.success("已归档");
                        }
                        //return ResultUtil.success(_flow_no);
                    } else {
                        return ResultUtil.error(500, "该流程已审核完成", "", null);
                    }
                }
            } else {
                return ResultUtil.error(500, "未查询到该流程", "", null);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result getFlowRecords(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _flow_no = jsonObject.getString("flow_no");
                String _flow_type = jsonObject.getString("flow_type");

                TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();

                if (_flow_no != null && !_flow_no.isEmpty()) {
                    tbFlowProcessRecords.setFlow_no(_flow_no);
                }

                if (_flow_type != null && !_flow_type.isEmpty()) {
                    tbFlowProcessRecords.setFlow_type(_flow_no);
                }

                return ResultUtil.success(tbFlowProcessRecordsDao.getTbFlowProcessRecordsList(tbFlowProcessRecords));

            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getFlowTemplateInfoByFlowNo(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _knowledge_base_key = jsonObject.getString("knowledge_base_key");

                if (_knowledge_base_key == null || _knowledge_base_key.isEmpty()) {
                    return ResultUtil.error(500, "_knowledge_base_key不可以为空", "", null);
                }

                String queryType = "key";
                String tempTemplate_type = "";

                //直接获取知识库数据
                List<TbKnowledgeBaseData> tbKnowledgeBaseDataList = tbKnowledgeBaseDataDao.getByBaseKey(_knowledge_base_key);
                if (tbKnowledgeBaseDataList != null && tbKnowledgeBaseDataList.size() > 0) {
                    //获取一下类别信息
                    tempTemplate_type = tbKnowledgeBaseDataList.get(0).getTemplate_type();

                    String _flow_type = "";
                    if (tempTemplate_type.equals("designType")) {
                        _flow_type = "design";
                    }
                    if (tempTemplate_type.equals("deviceType")) {
                        _flow_type = "device";
                    }

                    //获取流程信息
                    //先判断是否取到了标准流程的流程节点信息
                    List<TbFlowDetail> tbFlowDetails = tbFlowDetailDao.getFolwListByType(_flow_type);
                    if (tbFlowDetails == null || tbFlowDetails.size() <= 0) {
                        return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                    }

                    List<Map<String, Object>> combinedList = new ArrayList<>();

                    for (TbFlowDetail detail : tbFlowDetails) {
                        Map<String, Object> combinedMap = new HashMap<>();

                        combinedMap.put("flow_type", detail.getFlow_type());
                        combinedMap.put("flow_name", detail.getFlow_name());
                        combinedMap.put("flow_level", detail.getFlow_level());
                        combinedMap.put("knowledge_base_key", _knowledge_base_key);
                        combinedMap.put("flow_approver", detail.getFlow_approver());
                        combinedMap.put("sort", detail.getSort());
                        //combinedMap.put("create_time", flowInfo.getCreate_time());
                        combinedMap.put("create_user", detail.getCreate_user());
                        combinedMap.put("create_time", detail.getCreate_time());
                        combinedMap.put("update_time", detail.getUpdate_time());

                        combinedMap.put("update_user", detail.getUpdate_user());
                        combinedMap.put("remark", detail.getRemark());
                        //combinedMap.put("status", detail.getStatus());
                        String flowApprovers = detail.getFlow_approver();
                        if (flowApprovers != null && !flowApprovers.isEmpty()) {
                            // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                            List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));

                            combinedMap.put("flow_approver_list", flowApproverList);
                            combinedMap.put("flow_approver_info", user2Dao.getUserInfoByIds(flowApproverList));
                        }

                        combinedMap.put("flow_approver_authorize", detail.getFlow_approver_authorize());
                        combinedMap.put("comments", detail.getComments());
                        combinedMap.put("designer", detail.getDesigner());

                        if (detail.getFlow_level() == 1) {
                            Map<String, String> keyMap = new HashMap<>();

                            // 向 Map 中添加键值对
                            keyMap.put("basicInfo", tempTemplate_type);
                            keyMap.put("logInfo", "logInfo");
                            keyMap.put("application", "application");
                            keyMap.put("description", "description");

                            for (String key : keyMap.keySet()) {
                                String value = keyMap.get(key);

                                List<Map<String, Object>> listBasicInfo = new ArrayList<>();

                                String finalTempTemplate_type = tempTemplate_type;

                                List<TbKnowledgeBaseData> filteredList = tbKnowledgeBaseDataList.stream()
                                        .filter(TbTaskTemplateData -> Objects.equals(TbTaskTemplateData.getParent_param_key(), value))
                                        .collect(Collectors.toList());

                                if (filteredList != null && !filteredList.isEmpty()) {
                                    // 找到最大 row_sort 值
                                    Optional<Integer> maxRowSort = filteredList.stream()
                                            .map(TbKnowledgeBaseData::getRow_sort)
                                            .filter(Objects::nonNull) // 过滤掉 null 值
                                            .max(Integer::compareTo);

                                    int maxRowSortValue = maxRowSort.orElse(-1);

                                    for (int i = 0; i <= maxRowSortValue; i++) {
                                        Map<String, Object> basicInfo = new HashMap<>();
                                        for (TbKnowledgeBaseData tbKnowledgeBaseData : filteredList) {
                                            //Map<String, Object> basicInfo = new HashMap<>();
                                            if (tbKnowledgeBaseData.getRow_sort() == i) {
                                                if (tbKnowledgeBaseData.getParam_type() == 3 || tbKnowledgeBaseData.getParam_type() == 4) {
                                                    if (tbKnowledgeBaseData.getParam_value() != null) {
                                                        List<String> fileList = Arrays.asList(tbKnowledgeBaseData.getParam_value().split(","));
                                                        //List<TbKnowledgeBaseFile> aaa=tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                        //basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList));
                                                        List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                        tbKnowledgeBaseFileList.stream()
                                                                .filter(file -> file.getFile_type() != null && file.getFile_type() == 4)
                                                                .forEach(file -> {
                                                                    String base64 = "";
                                                                    if (env.equals("dev")) {
                                                                        base64 = s3UploadFileService.getImageBase64FromUrl(file.getUrl());
                                                                    } else {
                                                                        base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + file.getUrl());
                                                                    }
                                                                    file.setUrl(CommonUtils.base64Prefix() + base64);
                                                                });

                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseFileList);
                                                    } else {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                    }
                                                } else {

                                                    if (tbKnowledgeBaseData.getParam_value() != null && tbKnowledgeBaseData.getParam_value().startsWith("[")) {
                                                        ObjectMapper mapper = new ObjectMapper();
                                                        JsonNode rootNode = mapper.readTree(tbKnowledgeBaseData.getParam_value());
                                                        List<Object> resultList = new ArrayList<>();

                                                        for (JsonNode node : rootNode) {
                                                            if (node.isTextual()) {
                                                                resultList.add(node.asText()); // 字符串类型
                                                            } else if (node.isInt()) {
                                                                resultList.add(node.asInt()); // 整数类型
                                                            }
                                                        }
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), resultList);
                                                    } else {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                    }
                                                    //basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                }
                                            }
                                            //basicInfo.put("row", tbKnowledgeBaseData.getRow_sort());
                                            //listBasicInfo.add(basicInfo);
                                        }
                                        if (!basicInfo.isEmpty()) {
                                            //basicInfo.put("row", i);
                                            listBasicInfo.add(basicInfo);
                                        }
                                    }
                                    combinedMap.put(key, listBasicInfo);
                                }
                            }
                            //把模板结构也要同步过来
                            //combinedMap.put("tbTemplate", commonService.buildTree4(tbKnowledgeBaseDataList));
                            //if (_flow_type.equals("device")) {
                            //    //增加5个表的数据
                            //    combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(_flow_no, 1));
                            //}

                            if (_flow_type.equals("device") || _flow_type.equals("vpl")) {
                                //20250325  增加查询,先从列表里面把器件编号,封装名称查出来
                                // 定义动态目标参数集合（可扩展）
                                Set<String> targetParams = new HashSet<>(Arrays.asList("器件编码", "器件封装"));

                                // 执行筛选并生成结果映射
                                Map<String, TbKnowledgeBaseData> resultMap = tbKnowledgeBaseDataList.stream()
                                        .filter(item -> targetParams.contains(item.getParam_name()))
                                        .collect(Collectors.toMap(
                                                TbKnowledgeBaseData::getParam_name, // Key：param_name值
                                                Function.identity(),                // Value：对象本身
                                                (existing, replacement) -> existing // 解决键冲突（保留第一个）
                                        ));

                                TbKnowledgeBaseData componentCodeObj = resultMap.get("器件编码");

                                TbKnowledgeBaseData packageNameObj = resultMap.get("器件封装");

                                String Is_dense_comp = "";
                                String Pastemask_thickness_max = "";
                                String Pastemask_thickness_min = "";
                                String Pin_min_pitch = "";

                                //要先处理封装库的信息,因为VPL有字段来源封装
                                List<TbFlowCompPkg> tbFlowCompPkgList = new ArrayList<>();

                                if (packageNameObj != null) {
                                    if (packageNameObj.getParam_value() != null && !packageNameObj.getParam_value().isEmpty()) {
                                        List<vVplPackage> vplPackageList = _vVplPackageDao.getvVplPackage(packageNameObj.getParam_value());
                                        if (vplPackageList != null && vplPackageList.size() > 0) {
                                            for (vVplPackage source : vplPackageList) {
                                                TbFlowCompPkg target = new TbFlowCompPkg();

                                                // 手动映射同名同类型字段
                                                target.setPkg_name(source.getPkg_name());
                                                target.setAssembly_type(source.getAssembly_type());
                                                target.setFoot_num(source.getFoot_num());
                                                target.setBody_length(source.getBody_length());
                                                target.setBody_width(source.getBody_width());
                                                target.setPad_airgap_min(source.getPad_airgap_min());
                                                target.setPitch_o2c_x(source.getPitch_o2c_x());
                                                target.setPitch_o2c_y(source.getPitch_o2c_y());
                                                target.setIs_size_not_fit(source.getIs_size_not_fit());
                                                target.setIs_grid_design(source.getIs_grid_design());
                                                target.setIs_twins_design(source.getIs_twins_design());
                                                target.setIs_special_design(source.getIs_special_design());
                                                target.setIs_window_open(source.getIs_window_open());
                                                target.setIs_small_air_gap(source.getIs_small_air_gap());

                                                Is_dense_comp = source.getIs_dense_comp();
                                                Pastemask_thickness_max = source.getPastemask_thickness_max();
                                                Pastemask_thickness_min = source.getPastemask_thickness_min();
                                                Pin_min_pitch = source.getPin_min_pitch();

                                                tbFlowCompPkgList.add(target);
                                            }
                                        }
                                    }
                                }

                                if (tbFlowCompPkgList == null || tbFlowCompPkgList.size() <= 0) {
                                    TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                                    tbFlowCompPkgList.add(tbFlowCompPkg);
                                }

                                combinedMap.put("compPkg", tbFlowCompPkgList);

                                List<TbFlowCompVpl> tbFlowCompVplList = new ArrayList<>();
                                List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                //查询VPL表和封装库表
                                if (componentCodeObj != null) {
                                    if (componentCodeObj.getParam_value() != null && !componentCodeObj.getParam_value().isEmpty()) {
                                        List<vVplPartData> vVplPartDataList = _vVplPartDataDao.getvVplPartDataByCode(componentCodeObj.getParam_value());

                                        if (vVplPartDataList != null && vVplPartDataList.size() > 0) {

                                            Optional<Double> maxValueComponent_high_max = vVplPartDataList.stream()
                                                    // 过滤空值和空字符串（兼容带空格的无效数据）
                                                    .filter(obj -> obj.getComponent_high_max() != null && !obj.getComponent_high_max().trim().isEmpty())
                                                    // 正则去除单位（支持 MM/mm/Mm/mM 格式）
                                                    .map(obj -> obj.getComponent_high_max().replaceAll("(?i)mm$", ""))
                                                    // 转换为 Double（兼容科学计数法，如 1.5e2）
                                                    .flatMap(s -> {
                                                        try {
                                                            return Stream.of(Double.parseDouble(s.trim()));
                                                        } catch (NumberFormatException e) {
                                                            return Stream.empty(); // 忽略无效数值
                                                        }
                                                    })
                                                    // 求最大值
                                                    .max(Double::compare);

                                            String maxValueComponent_high_max_str = "";

                                            if (maxValueComponent_high_max.isPresent()) {
                                                maxValueComponent_high_max_str = maxValueComponent_high_max.get().toString();
                                            }

                                            //取第一个对象,转换成CompVpl的对象
                                            vVplPartData vVplPartDataObj = vVplPartDataList.get(0);

                                            TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                            // 将 vVplPartData 对象的属性值复制到 tbFlowCompVpl 对象中
                                            // 这里假设 TbFlowCompVpl 类有相应的 setter 方法
                                            tbFlowCompVpl.setFlow_no(vVplPartDataObj.getCode());
                                            tbFlowCompVpl.setFlow_level(1);
                                            tbFlowCompVpl.setComp_code(vVplPartDataObj.getCode());
                                            tbFlowCompVpl.setComp_type(vVplPartDataObj.getComp_type());
                                            tbFlowCompVpl.setPkg_name(vVplPartDataObj.getPkg_name());
                                            tbFlowCompVpl.setAssembly_type(vVplPartDataObj.getAssembly_type());
                                            tbFlowCompVpl.setComponent_high_max_vpl(maxValueComponent_high_max_str);
                                            tbFlowCompVpl.setPin_high_max(vVplPartDataObj.getPin_high_max());
                                            tbFlowCompVpl.setPin_high_min(vVplPartDataObj.getPin_high_min());
                                            tbFlowCompVpl.setPth_diameter_min(vVplPartDataObj.getPth_diameter_min());
                                            tbFlowCompVpl.setIs_tht_power(vVplPartDataObj.getIs_tht_power());
                                            tbFlowCompVpl.setIs_tht_capcitor(vVplPartDataObj.getIs_tht_capcitor());
                                            tbFlowCompVpl.setIs_glue(vVplPartDataObj.getIs_glue());
                                            tbFlowCompVpl.setIs_little_retentionforce(vVplPartDataObj.getIs_little_retentionforce());
                                            //数据在封装里面
                                            tbFlowCompVpl.setIs_dense_comp(Is_dense_comp);
                                            tbFlowCompVpl.setPastemask_thickness_max(Pastemask_thickness_max);
                                            tbFlowCompVpl.setPastemask_thickness_min(Pastemask_thickness_min);
                                            tbFlowCompVpl.setPin_min_pitch(Pin_min_pitch);

                                            // 将转换后的 TbFlowCompVpl 对象添加到列表中
                                            tbFlowCompVplList.add(tbFlowCompVpl);

                                            for (vVplPartData source : vVplPartDataList) {
                                                TbFlowCompManufacturer target = new TbFlowCompManufacturer();

                                                // 映射同名同类型字段
                                                target.setManufacturer(source.getManufacturer());
                                                target.setManufacturer_type(source.getManufacturer_type());
                                                target.setWeight(source.getWeight());
                                                target.setCoplanarity(source.getCoplanarity());
                                                target.setStandoff(source.getStandoff());
                                                target.setSolder_tg_max(source.getSolder_tg_max());
                                                target.setBga_height_min(source.getBga_height_min());
                                                target.setUnbd_thickness_min(source.getUnbd_thickness_min());
                                                target.setBoard_thickness_min(source.getBoard_thickness_min());
                                                target.setBoard_thickness_max(source.getBoard_thickness_max());
                                                target.setIs_secd_reflow_drop(source.getIs_secd_reflow_drop());
                                                tbFlowCompManufacturerList.add(target);
                                            }
                                        }
                                    }
                                }

                                if (tbFlowCompVplList == null || tbFlowCompVplList.size() <= 0) {
                                    TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                    tbFlowCompVplList.add(tbFlowCompVpl);
                                }

                                //if(tbFlowCompManufacturerList==null ||tbFlowCompManufacturerList.size()<=0)
                                //{
                                //    TbFlowCompManufacturer tbFlowCompManufacturer=new TbFlowCompManufacturer();
                                //    tbFlowCompManufacturerList.add(tbFlowCompManufacturer);
                                //}

                                combinedMap.put("compVpl", tbFlowCompVplList);
                                combinedMap.put("compManufacturer", tbFlowCompManufacturerList);
                            }
                        }

                        combinedList.add(combinedMap);
                    }

                    return ResultUtil.success(combinedList);
                } else {
                    return ResultUtil.error(500, "未查询到知识库数据,请刷新数据!", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getFlowTemplateInfoByFlowNo2(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _knowledge_base_key = jsonObject.getString("knowledge_base_key");

                if (_knowledge_base_key == null || _knowledge_base_key.isEmpty()) {
                    return ResultUtil.error(500, "_knowledge_base_key不可以为空", "", null);
                }

                String queryType = "key";
                String tempTemplate_type = "";

                //直接获取知识库数据
                List<TbKnowledgeBaseData> tbKnowledgeBaseDataList = tbKnowledgeBaseDataDao.getByBaseKey(_knowledge_base_key);
                if (tbKnowledgeBaseDataList != null && tbKnowledgeBaseDataList.size() > 0) {
                    //获取一下类别信息
                    tempTemplate_type = tbKnowledgeBaseDataList.get(0).getTemplate_type();

                    String _flow_type = "";
                    if (tempTemplate_type.equals("designType")) {
                        _flow_type = "design";
                    }
                    if (tempTemplate_type.equals("deviceType")) {
                        _flow_type = "device";
                    }

                    //获取流程信息
                    //先判断是否取到了标准流程的流程节点信息
                    List<TbFlowDetail> tbFlowDetails = tbFlowDetailDao.getFolwListByType(_flow_type);
                    if (tbFlowDetails == null || tbFlowDetails.size() <= 0) {
                        return ResultUtil.error(500, "没有取到流程节点信息", "", null);
                    }

                    List<Map<String, Object>> combinedList = new ArrayList<>();

                    for (TbFlowDetail detail : tbFlowDetails) {
                        Map<String, Object> combinedMap = new HashMap<>();

                        combinedMap.put("flow_type", detail.getFlow_type());
                        combinedMap.put("flow_name", detail.getFlow_name());
                        combinedMap.put("flow_level", detail.getFlow_level());
                        combinedMap.put("knowledge_base_key", _knowledge_base_key);
                        combinedMap.put("flow_approver", detail.getFlow_approver());
                        combinedMap.put("sort", detail.getSort());
                        //combinedMap.put("create_time", flowInfo.getCreate_time());
                        combinedMap.put("create_user", detail.getCreate_user());
                        combinedMap.put("create_time", detail.getCreate_time());
                        combinedMap.put("update_time", detail.getUpdate_time());

                        combinedMap.put("update_user", detail.getUpdate_user());
                        combinedMap.put("remark", detail.getRemark());
                        //combinedMap.put("status", detail.getStatus());
                        String flowApprovers = detail.getFlow_approver();
                        if (flowApprovers != null && !flowApprovers.isEmpty()) {
                            // 使用逗号分隔 flowApprovers 字符串，并转换为 List
                            List<String> flowApproverList = Arrays.asList(flowApprovers.split(","));

                            combinedMap.put("flow_approver_list", flowApproverList);
                            combinedMap.put("flow_approver_info", user2Dao.getUserInfoByIds(flowApproverList));
                        }

                        combinedMap.put("flow_approver_authorize", detail.getFlow_approver_authorize());
                        combinedMap.put("comments", detail.getComments());
                        combinedMap.put("designer", detail.getDesigner());

                        if (detail.getFlow_level() == 1) {
                            Map<String, String> keyMap = new HashMap<>();

                            // 向 Map 中添加键值对
                            keyMap.put("basicInfo", tempTemplate_type);
                            keyMap.put("logInfo", "logInfo");
                            keyMap.put("application", "application");
                            keyMap.put("description", "description");

                            for (String key : keyMap.keySet()) {
                                String value = keyMap.get(key);

                                List<Map<String, Object>> listBasicInfo = new ArrayList<>();

                                String finalTempTemplate_type = tempTemplate_type;

                                List<TbKnowledgeBaseData> filteredList = tbKnowledgeBaseDataList.stream()
                                        .filter(TbTaskTemplateData -> Objects.equals(TbTaskTemplateData.getParent_param_key(), value))
                                        .collect(Collectors.toList());

                                if (filteredList != null && !filteredList.isEmpty()) {
                                    // 找到最大 row_sort 值
                                    Optional<Integer> maxRowSort = filteredList.stream()
                                            .map(TbKnowledgeBaseData::getRow_sort)
                                            .filter(Objects::nonNull) // 过滤掉 null 值
                                            .max(Integer::compareTo);

                                    int maxRowSortValue = maxRowSort.orElse(-1);

                                    for (int i = 0; i <= maxRowSortValue; i++) {
                                        Map<String, Object> basicInfo = new HashMap<>();
                                        for (TbKnowledgeBaseData tbKnowledgeBaseData : filteredList) {
                                            //Map<String, Object> basicInfo = new HashMap<>();
                                            if (tbKnowledgeBaseData.getRow_sort() == i) {
                                                if (tbKnowledgeBaseData.getParam_type() == 2) {
                                                    Optional<TbKnowledgeBaseData> optionalTbTaskTemplateData = tbKnowledgeBaseDataList.stream()
                                                            .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(tbKnowledgeBaseData.getParam_value()))
                                                            .findAny();

                                                    if (optionalTbTaskTemplateData.isPresent()) {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), optionalTbTaskTemplateData.get().getParam_name());
                                                    } else {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), "");
                                                    }
                                                } else if (tbKnowledgeBaseData.getParam_type() == 5) {
                                                    if (tbKnowledgeBaseData.getParam_value() != null && tbKnowledgeBaseData.getParam_value().startsWith("[")) {
                                                        ObjectMapper mapper = new ObjectMapper();
                                                        JsonNode rootNode = mapper.readTree(tbKnowledgeBaseData.getParam_value());
                                                        List<Object> resultList = new ArrayList<>();

                                                        for (JsonNode node : rootNode) {
                                                            Optional<TbKnowledgeBaseData> optionalTbTaskTemplateData = tbKnowledgeBaseDataList.stream()
                                                                    .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_key().equals(node.asText()))
                                                                    .findAny();

                                                            if (optionalTbTaskTemplateData.isPresent()) {
                                                                resultList.add(optionalTbTaskTemplateData.get().getParam_name());
                                                            }
                                                        }
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), resultList);
                                                    }
                                                }
                                                else if (tbKnowledgeBaseData.getParam_type() == 3 || tbKnowledgeBaseData.getParam_type() == 4) {
                                                    if (tbKnowledgeBaseData.getParam_value() != null) {
                                                        List<String> fileList = Arrays.asList(tbKnowledgeBaseData.getParam_value().split(","));
                                                        //List<TbKnowledgeBaseFile> aaa=tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                        //basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList));
                                                        List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = tbKnowledgeBaseFileDao.getTbKnowledgeBaseFileByParams(fileList);
                                                        tbKnowledgeBaseFileList.stream()
                                                                .filter(file -> file.getFile_type() != null && file.getFile_type() == 4)
                                                                .forEach(file -> {
                                                                    String base64 = "";
                                                                    if (env.equals("dev")) {
                                                                        base64 = s3UploadFileService.getImageBase64FromUrl(file.getUrl());
                                                                    } else {
                                                                        base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + file.getUrl());
                                                                    }
                                                                    file.setUrl(CommonUtils.base64Prefix() + base64);
                                                                });

                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseFileList);
                                                    } else {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                    }
                                                } else {

                                                    if (tbKnowledgeBaseData.getParam_value() != null && tbKnowledgeBaseData.getParam_value().startsWith("[")) {
                                                        ObjectMapper mapper = new ObjectMapper();
                                                        JsonNode rootNode = mapper.readTree(tbKnowledgeBaseData.getParam_value());
                                                        List<Object> resultList = new ArrayList<>();

                                                        for (JsonNode node : rootNode) {
                                                            if (node.isTextual()) {
                                                                resultList.add(node.asText()); // 字符串类型
                                                            } else if (node.isInt()) {
                                                                resultList.add(node.asInt()); // 整数类型
                                                            }
                                                        }
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), resultList);
                                                    } else {
                                                        basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                    }
                                                    //basicInfo.put(tbKnowledgeBaseData.getParam_key(), tbKnowledgeBaseData.getParam_value());
                                                }
                                            }
                                            //basicInfo.put("row", tbKnowledgeBaseData.getRow_sort());
                                            //listBasicInfo.add(basicInfo);
                                        }
                                        if (!basicInfo.isEmpty()) {
                                            //basicInfo.put("row", i);
                                            listBasicInfo.add(basicInfo);
                                        }
                                    }
                                    combinedMap.put(key, listBasicInfo);
                                }
                            }
                            //把模板结构也要同步过来
                            //combinedMap.put("tbTemplate", commonService.buildTree4(tbKnowledgeBaseDataList));
                            //if (_flow_type.equals("device")) {
                            //    //增加5个表的数据
                            //    combinedMap.put("compVpl", tbFlowCompVplDao.getTbFlowCompVplByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compPkg", tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compManufacturer", tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compVplAttr", tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(_flow_no, 1));
                            //    combinedMap.put("compVplPinAttr", tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(_flow_no, 1));
                            //}

                            if (_flow_type.equals("device") || _flow_type.equals("vpl")) {
                                //20250325  增加查询,先从列表里面把器件编号,封装名称查出来
                                // 定义动态目标参数集合（可扩展）
                                Set<String> targetParams = new HashSet<>(Arrays.asList("器件编码", "器件封装"));

                                // 执行筛选并生成结果映射
                                Map<String, TbKnowledgeBaseData> resultMap = tbKnowledgeBaseDataList.stream()
                                        .filter(item -> targetParams.contains(item.getParam_name()))
                                        .collect(Collectors.toMap(
                                                TbKnowledgeBaseData::getParam_name, // Key：param_name值
                                                Function.identity(),                // Value：对象本身
                                                (existing, replacement) -> existing // 解决键冲突（保留第一个）
                                        ));

                                TbKnowledgeBaseData componentCodeObj = resultMap.get("器件编码");

                                TbKnowledgeBaseData packageNameObj = resultMap.get("器件封装");

                                String Is_dense_comp = "";
                                String Pastemask_thickness_max = "";
                                String Pastemask_thickness_min = "";
                                String Pin_min_pitch = "";

                                //要先处理封装库的信息,因为VPL有字段来源封装
                                List<TbFlowCompPkg> tbFlowCompPkgList = new ArrayList<>();

                                if (packageNameObj != null) {
                                    if (packageNameObj.getParam_value() != null && !packageNameObj.getParam_value().isEmpty()) {
                                        List<vVplPackage> vplPackageList = _vVplPackageDao.getvVplPackage(packageNameObj.getParam_value());
                                        if (vplPackageList != null && vplPackageList.size() > 0) {
                                            for (vVplPackage source : vplPackageList) {
                                                TbFlowCompPkg target = new TbFlowCompPkg();

                                                // 手动映射同名同类型字段
                                                target.setPkg_name(source.getPkg_name());
                                                target.setAssembly_type(source.getAssembly_type());
                                                target.setFoot_num(source.getFoot_num());
                                                target.setBody_length(source.getBody_length());
                                                target.setBody_width(source.getBody_width());
                                                target.setPad_airgap_min(source.getPad_airgap_min());
                                                target.setPitch_o2c_x(source.getPitch_o2c_x());
                                                target.setPitch_o2c_y(source.getPitch_o2c_y());
                                                target.setIs_size_not_fit(source.getIs_size_not_fit());
                                                target.setIs_grid_design(source.getIs_grid_design());
                                                target.setIs_twins_design(source.getIs_twins_design());
                                                target.setIs_special_design(source.getIs_special_design());
                                                target.setIs_window_open(source.getIs_window_open());
                                                target.setIs_small_air_gap(source.getIs_small_air_gap());

                                                Is_dense_comp = source.getIs_dense_comp();
                                                Pastemask_thickness_max = source.getPastemask_thickness_max();
                                                Pastemask_thickness_min = source.getPastemask_thickness_min();
                                                Pin_min_pitch = source.getPin_min_pitch();

                                                tbFlowCompPkgList.add(target);
                                            }
                                        }
                                    }
                                }

                                if (tbFlowCompPkgList == null || tbFlowCompPkgList.size() <= 0) {
                                    TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                                    tbFlowCompPkgList.add(tbFlowCompPkg);
                                }

                                combinedMap.put("compPkg", tbFlowCompPkgList);

                                List<TbFlowCompVpl> tbFlowCompVplList = new ArrayList<>();
                                List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                                //查询VPL表和封装库表
                                if (componentCodeObj != null) {
                                    if (componentCodeObj.getParam_value() != null && !componentCodeObj.getParam_value().isEmpty()) {
                                        List<vVplPartData> vVplPartDataList = _vVplPartDataDao.getvVplPartDataByCode(componentCodeObj.getParam_value());

                                        if (vVplPartDataList != null && vVplPartDataList.size() > 0) {

                                            Optional<Double> maxValueComponent_high_max = vVplPartDataList.stream()
                                                    // 过滤空值和空字符串（兼容带空格的无效数据）
                                                    .filter(obj -> obj.getComponent_high_max() != null && !obj.getComponent_high_max().trim().isEmpty())
                                                    // 正则去除单位（支持 MM/mm/Mm/mM 格式）
                                                    .map(obj -> obj.getComponent_high_max().replaceAll("(?i)mm$", ""))
                                                    // 转换为 Double（兼容科学计数法，如 1.5e2）
                                                    .flatMap(s -> {
                                                        try {
                                                            return Stream.of(Double.parseDouble(s.trim()));
                                                        } catch (NumberFormatException e) {
                                                            return Stream.empty(); // 忽略无效数值
                                                        }
                                                    })
                                                    // 求最大值
                                                    .max(Double::compare);

                                            String maxValueComponent_high_max_str = "";

                                            if (maxValueComponent_high_max.isPresent()) {
                                                maxValueComponent_high_max_str = maxValueComponent_high_max.get().toString();
                                            }

                                            //取第一个对象,转换成CompVpl的对象
                                            vVplPartData vVplPartDataObj = vVplPartDataList.get(0);

                                            TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                            // 将 vVplPartData 对象的属性值复制到 tbFlowCompVpl 对象中
                                            // 这里假设 TbFlowCompVpl 类有相应的 setter 方法
                                            tbFlowCompVpl.setFlow_no(vVplPartDataObj.getCode());
                                            tbFlowCompVpl.setFlow_level(1);
                                            tbFlowCompVpl.setComp_code(vVplPartDataObj.getCode());
                                            tbFlowCompVpl.setComp_type(vVplPartDataObj.getComp_type());
                                            tbFlowCompVpl.setPkg_name(vVplPartDataObj.getPkg_name());
                                            tbFlowCompVpl.setAssembly_type(vVplPartDataObj.getAssembly_type());
                                            tbFlowCompVpl.setComponent_high_max_vpl(maxValueComponent_high_max_str);
                                            tbFlowCompVpl.setPin_high_max(vVplPartDataObj.getPin_high_max());
                                            tbFlowCompVpl.setPin_high_min(vVplPartDataObj.getPin_high_min());
                                            tbFlowCompVpl.setPth_diameter_min(vVplPartDataObj.getPth_diameter_min());
                                            tbFlowCompVpl.setIs_tht_power(vVplPartDataObj.getIs_tht_power());
                                            tbFlowCompVpl.setIs_tht_capcitor(vVplPartDataObj.getIs_tht_capcitor());
                                            tbFlowCompVpl.setIs_glue(vVplPartDataObj.getIs_glue());
                                            tbFlowCompVpl.setIs_little_retentionforce(vVplPartDataObj.getIs_little_retentionforce());
                                            //数据在封装里面
                                            tbFlowCompVpl.setIs_dense_comp(Is_dense_comp);
                                            tbFlowCompVpl.setPastemask_thickness_max(Pastemask_thickness_max);
                                            tbFlowCompVpl.setPastemask_thickness_min(Pastemask_thickness_min);
                                            tbFlowCompVpl.setPin_min_pitch(Pin_min_pitch);

                                            // 将转换后的 TbFlowCompVpl 对象添加到列表中
                                            tbFlowCompVplList.add(tbFlowCompVpl);

                                            for (vVplPartData source : vVplPartDataList) {
                                                TbFlowCompManufacturer target = new TbFlowCompManufacturer();

                                                // 映射同名同类型字段
                                                target.setManufacturer(source.getManufacturer());
                                                target.setManufacturer_type(source.getManufacturer_type());
                                                target.setWeight(source.getWeight());
                                                target.setCoplanarity(source.getCoplanarity());
                                                target.setStandoff(source.getStandoff());
                                                target.setSolder_tg_max(source.getSolder_tg_max());
                                                target.setBga_height_min(source.getBga_height_min());
                                                target.setUnbd_thickness_min(source.getUnbd_thickness_min());
                                                target.setBoard_thickness_min(source.getBoard_thickness_min());
                                                target.setBoard_thickness_max(source.getBoard_thickness_max());
                                                target.setIs_secd_reflow_drop(source.getIs_secd_reflow_drop());
                                                tbFlowCompManufacturerList.add(target);
                                            }
                                        }
                                    }
                                }

                                if (tbFlowCompVplList == null || tbFlowCompVplList.size() <= 0) {
                                    TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                                    tbFlowCompVplList.add(tbFlowCompVpl);
                                }

                                //if(tbFlowCompManufacturerList==null ||tbFlowCompManufacturerList.size()<=0)
                                //{
                                //    TbFlowCompManufacturer tbFlowCompManufacturer=new TbFlowCompManufacturer();
                                //    tbFlowCompManufacturerList.add(tbFlowCompManufacturer);
                                //}

                                combinedMap.put("compVpl", tbFlowCompVplList);
                                combinedMap.put("compManufacturer", tbFlowCompManufacturerList);
                            }
                        }

                        combinedList.add(combinedMap);
                    }

                    return ResultUtil.success(combinedList);
                } else {
                    return ResultUtil.error(500, "未查询到知识库数据,请刷新数据!", "", null);
                }
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }
    @Override
    public Result getCompPkgInfoByCompPkg(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _comp_code = jsonObject.getString("comp_code");
                String _pkg_name = jsonObject.getString("pkg_name");

                //List<Map<String, Object>> combinedList = new ArrayList<>();

                Map<String, Object> combinedMap = new HashMap<>();
                String Is_dense_comp = "";
                String Pastemask_thickness_max = "";
                String Pastemask_thickness_min = "";
                String Pin_min_pitch = "";

                //要先处理封装库的信息,因为VPL有字段来源封装
                List<TbFlowCompPkg> tbFlowCompPkgList = new ArrayList<>();

                if (_pkg_name != null && !_pkg_name.isEmpty()) {
                    List<vVplPackage> vplPackageList = _vVplPackageDao.getvVplPackage(_pkg_name);
                    if (vplPackageList != null && vplPackageList.size() > 0) {
                        for (vVplPackage source : vplPackageList) {
                            TbFlowCompPkg target = new TbFlowCompPkg();

                            // 手动映射同名同类型字段
                            target.setPkg_name(source.getPkg_name());
                            target.setAssembly_type(source.getAssembly_type());
                            target.setFoot_num(source.getFoot_num());
                            target.setBody_length(source.getBody_length());
                            target.setBody_width(source.getBody_width());
                            target.setPad_airgap_min(source.getPad_airgap_min());
                            target.setPitch_o2c_x(source.getPitch_o2c_x());
                            target.setPitch_o2c_y(source.getPitch_o2c_y());
                            target.setIs_size_not_fit(source.getIs_size_not_fit());
                            target.setIs_grid_design(source.getIs_grid_design());
                            target.setIs_twins_design(source.getIs_twins_design());
                            target.setIs_special_design(source.getIs_special_design());
                            target.setIs_window_open(source.getIs_window_open());
                            target.setIs_small_air_gap(source.getIs_small_air_gap());

                            Is_dense_comp = source.getIs_dense_comp();
                            Pastemask_thickness_max = source.getPastemask_thickness_max();
                            Pastemask_thickness_min = source.getPastemask_thickness_min();
                            Pin_min_pitch = source.getPin_min_pitch();

                            tbFlowCompPkgList.add(target);
                        }
                    }
                }

                if (tbFlowCompPkgList == null || tbFlowCompPkgList.size() <= 0) {
                    TbFlowCompPkg tbFlowCompPkg = new TbFlowCompPkg();
                    tbFlowCompPkgList.add(tbFlowCompPkg);
                }

                combinedMap.put("compPkg", tbFlowCompPkgList);

                List<TbFlowCompVpl> tbFlowCompVplList = new ArrayList<>();
                List<TbFlowCompManufacturer> tbFlowCompManufacturerList = new ArrayList<>();
                //查询VPL表和封装库表
                if (_comp_code != null && !_comp_code.isEmpty()) {
                    List<vVplPartData> vVplPartDataList = _vVplPartDataDao.getvVplPartDataByCode(_comp_code);
                    if (vVplPartDataList != null && vVplPartDataList.size() > 0) {
                        //取第一个对象,转换成CompVpl的对象
                        vVplPartData vVplPartDataObj = vVplPartDataList.get(0);

                        TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                        // 将 vVplPartData 对象的属性值复制到 tbFlowCompVpl 对象中
                        // 这里假设 TbFlowCompVpl 类有相应的 setter 方法
                        tbFlowCompVpl.setFlow_no(vVplPartDataObj.getCode());
                        tbFlowCompVpl.setFlow_level(1);
                        tbFlowCompVpl.setComp_code(vVplPartDataObj.getCode());
                        tbFlowCompVpl.setComp_type(vVplPartDataObj.getComp_type());
                        tbFlowCompVpl.setPkg_name(vVplPartDataObj.getPkg_name());
                        tbFlowCompVpl.setAssembly_type(vVplPartDataObj.getAssembly_type());
                        tbFlowCompVpl.setComponent_high_max_vpl(vVplPartDataObj.getHigh_max_vpl());
                        tbFlowCompVpl.setPin_high_max(vVplPartDataObj.getPin_high_max());
                        tbFlowCompVpl.setPin_high_min(vVplPartDataObj.getPin_high_min());
                        tbFlowCompVpl.setPth_diameter_min(vVplPartDataObj.getPth_diameter_min());
                        tbFlowCompVpl.setIs_tht_power(vVplPartDataObj.getIs_tht_power());
                        tbFlowCompVpl.setIs_tht_capcitor(vVplPartDataObj.getIs_tht_capcitor());
                        tbFlowCompVpl.setIs_glue(vVplPartDataObj.getIs_glue());
                        tbFlowCompVpl.setIs_little_retentionforce(vVplPartDataObj.getIs_little_retentionforce());
                        //数据在封装里面
                        tbFlowCompVpl.setIs_dense_comp(Is_dense_comp);
                        tbFlowCompVpl.setPastemask_thickness_max(Pastemask_thickness_max);
                        tbFlowCompVpl.setPastemask_thickness_min(Pastemask_thickness_min);
                        tbFlowCompVpl.setPin_min_pitch(Pin_min_pitch);

                        // 将转换后的 TbFlowCompVpl 对象添加到列表中
                        tbFlowCompVplList.add(tbFlowCompVpl);

                        for (vVplPartData source : vVplPartDataList) {
                            TbFlowCompManufacturer target = new TbFlowCompManufacturer();

                            // 映射同名同类型字段
                            target.setManufacturer(source.getManufacturer());
                            target.setManufacturer_type(source.getManufacturer_type());
                            target.setWeight(source.getWeight());
                            target.setCoplanarity(source.getCoplanarity());
                            target.setStandoff(source.getStandoff());
                            target.setSolder_tg_max(source.getSolder_tg_max());
                            target.setBga_height_min(source.getBga_height_min());
                            target.setUnbd_thickness_min(source.getUnbd_thickness_min());
                            target.setBoard_thickness_min(source.getBoard_thickness_min());
                            target.setBoard_thickness_max(source.getBoard_thickness_max());
                            target.setIs_secd_reflow_drop(source.getIs_secd_reflow_drop());
                            tbFlowCompManufacturerList.add(target);
                        }

                    }
                }

                if (tbFlowCompVplList == null || tbFlowCompVplList.size() <= 0) {
                    TbFlowCompVpl tbFlowCompVpl = new TbFlowCompVpl();
                    tbFlowCompVplList.add(tbFlowCompVpl);
                }

                combinedMap.put("compVpl", tbFlowCompVplList);
                combinedMap.put("compManufacturer", tbFlowCompManufacturerList);

                //combinedList.add(combinedMap);

                return ResultUtil.success(combinedMap);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getPkgByCompCode(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _comp_code = jsonObject.getString("comp_code");
                String _pkg_name = "";
                if(_comp_code!=null&&!_comp_code.isEmpty())
                {
                    List<vVplPartData> vplParts= _vVplPartDataDao.getvVplPartDataByCode(_comp_code);

                    if (vplParts != null && !vplParts.isEmpty()) {
                        _pkg_name = vplParts.stream()
                                .map(vVplPartData::getPkg_name) // 提取pkg_name字段
                                .filter(name -> name != null && !name.trim().isEmpty()) // 过滤掉null和空值
                                .distinct() // 去重[6,8](@ref)
                                .findFirst() // 取第一个元素[9,10](@ref)
                                .orElse(null); // 如果流为空则返回null
                    }
                }
                return ResultUtil.success(_pkg_name);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result deleteKnowledgeBaseByKey(String data) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _knowledge_base_key = jsonObject.getString("knowledge_base_key");
                String _flow_no = jsonObject.getString("flow_no");

                if (_knowledge_base_key == null || _knowledge_base_key.isEmpty()) {
                    return ResultUtil.error(500, "knowledge_base_key不允许为空", "", null);
                }

                //校验是不是管理员
                if (!(UserHeaderHolder.getRoleList().contains(1) || UserHeaderHolder.getRoleList().contains(2))) {
                    return ResultUtil.error(500, "只有管理员可以删除知识库信息", "", null);
                }
                TbKnowledgeBaseData tbKnowledgeBaseData = new TbKnowledgeBaseData();
                tbKnowledgeBaseData.setKnowledge_base_key(_knowledge_base_key);

                tbKnowledgeBaseDataDao.deleteTaskTemplateData(tbKnowledgeBaseData);

                TbFlowProcessRecords tbFlowProcessRecords = new TbFlowProcessRecords();
                tbFlowProcessRecords.setFlow_no(_flow_no);
                //tbFlowProcessRecords.setFlow_type("vpl");
                tbFlowProcessRecords.setFlow_name("管理员删除知识库");
                tbFlowProcessRecords.setResult("删除成功");
                tbFlowProcessRecords.setCreate_time(new Date());
                tbFlowProcessRecords.setCreate_user(UserHeaderHolder.getUserId());
                tbFlowProcessRecordsDao.insertFlowProcessRecords(tbFlowProcessRecords);

                //删除一下推送规则
                List<String> tempKey = new ArrayList<>();
                tempKey.add(_knowledge_base_key);
                tbKnowledgeBasePushLogicDao.deleteByBaseKey(tempKey);

                return ResultUtil.success("删除成功");
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getKnowledgeBaseNotice(String data) {
        try {
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _type = jsonObject.getString("type");

                if (_type == null || _type.isEmpty()) {
                    return ResultUtil.error(500, "type不可以为空", "", null);
                }
                String _attrName = "knowledge_base_" + _type;

                TbKnowledgeBaseConfig tbKnowledgeBaseConfig = tbKnowledgeBaseConfigDao.getByName2(_attrName);

                JSONObject jsonObjectReturn = new JSONObject();
                jsonObjectReturn.put("type", _attrName);
                jsonObjectReturn.put("attachment", null);

                if (tbKnowledgeBaseConfig == null) {
                    TbKnowledgeBaseConfig tbKnowledgeBaseConfig1 = new TbKnowledgeBaseConfig();
                    jsonObjectReturn.put("rule", tbKnowledgeBaseConfig1);
                } else {
                    jsonObjectReturn.put("rule", tbKnowledgeBaseConfig);
                }

                return ResultUtil.success(jsonObjectReturn);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result updateKnowledgeBaseNotice(String data) {
        try {
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _type = jsonObject.getString("type");
                String _ruleContent = jsonObject.getString("ruleContent");

                if (_type == null || _type.isEmpty()) {
                    return ResultUtil.error(500, "type不可以为空", "", null);
                }
                String _attrName = "knowledge_base_" + _type;

                List<TbKnowledgeBaseConfig> tbKnowledgeBaseConfigList = tbKnowledgeBaseConfigDao.getByName(_attrName);

                TbKnowledgeBaseConfig tbKnowledgeBaseConfig = new TbKnowledgeBaseConfig();

                if (tbKnowledgeBaseConfigList != null && tbKnowledgeBaseConfigList.size() > 0) {
                    tbKnowledgeBaseConfig.setAttr_name(_attrName);
                    tbKnowledgeBaseConfig.setAttr_value(_ruleContent);
                    tbKnowledgeBaseConfig.setUpdate_time(new Date());
                    tbKnowledgeBaseConfig.setUpdate_user(UserHeaderHolder.getUserId());

                    tbKnowledgeBaseConfigDao.UpdateTbKnowledgeBaseConfigByName(tbKnowledgeBaseConfig);
                } else {
                    tbKnowledgeBaseConfig.setAttr_name(_attrName);
                    tbKnowledgeBaseConfig.setAttr_value(_ruleContent);
                    tbKnowledgeBaseConfig.setCreate_time(new Date());
                    tbKnowledgeBaseConfig.setCreate_user(UserHeaderHolder.getUserId());
                    tbKnowledgeBaseConfig.setRemark(_type + "知识库描述");
                    tbKnowledgeBaseConfig.setAttr_desc(_type + "知识库描述");

                    List<TbKnowledgeBaseConfig> tbKnowledgeBaseConfigList1 = new ArrayList<>();
                    tbKnowledgeBaseConfigList1.add(tbKnowledgeBaseConfig);
                    tbKnowledgeBaseConfigDao.insertTbKnowledgeBaseConfigBatch(tbKnowledgeBaseConfigList1);
                }

                return ResultUtil.success("更新成功");
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    @Override
    public Result getDesignLogicByKnowledgeBaseKey(String data) {
        try {
            if (data != null && !data.isEmpty()) {
                JSONObject jsonObject = JSONObject.parseObject(data);

                String _knowledge_base_key = jsonObject.getString("knowledge_base_key");

                //if(_knowledge_base_key==null || _knowledge_base_key.isEmpty())
                //{
                //    return ResultUtil.error(500, "knowledge_base_key不可以为空", "", null);
                //}
                String rule = null;
                List<TbKnowledgeBasePushLogic> logics = null;
                String ruleDetail = "";

                if (_knowledge_base_key != null && !_knowledge_base_key.isEmpty()) {
                    logics = tbKnowledgeBasePushLogicDao.getByBaseKey(_knowledge_base_key);
                    // ? order by sort不起作用，使用map自带的排序功能
                    Map<Integer, String> ruleDetailMap = new HashMap<>();

                    for (TbKnowledgeBasePushLogic l : logics) {
                        rule = ". " + l.getBoardParamTypeName() + " "
                                + l.getBoardParamName() + " "
                                + ruleMap.get(l.getLogicRule()) + " "
                                + l.getLogicValue() + "\n";
                        ruleDetailMap.put(l.getSort() + 1, rule);
                    }
                    for (Map.Entry<Integer, String> ruleEntry : ruleDetailMap.entrySet()) {
                        ruleDetail += ruleEntry.getKey() + ruleEntry.getValue();
                    }
                }

                JSONObject temp = new JSONObject();
                temp.put("knowledgeBaseLogic", logics);
                temp.put("ruleDetail", ruleDetail);

                return ResultUtil.success(temp);
            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }


    public List<TbTaskTemplateData> getValuesFromJson(String _flow_no, JSONObject json, List<TbTaskTemplateData> inputList) {
        List<TbTaskTemplateData> resultList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将 JSON 字符串解析为 Map 对象
            //Map<String, Object> jsonMap = objectMapper.readValue(json, HashMap.class);

            for (TbTaskTemplateData inputParam : inputList) {
                String paramKey = inputParam.getParam_key();
                String param_parent_key = inputParam.getParent_param_key();

                String _param_parent_key = "";

                if (param_parent_key != null) {
                    if (param_parent_key.equals("designType") || param_parent_key.equals("deviceType")) {
                        _param_parent_key = "basicInfo";
                    } else {
                        _param_parent_key = param_parent_key;
                    }

                    //获取当前数据库中最大的行数值
                    Optional<Integer> maxRowSort = inputList.stream()
                            .filter(Objects::nonNull) // 过滤掉 null 值
                            .filter(entity -> entity.getParam_key().equals(paramKey) && entity.getRow_sort() != null)
                            .map(TbTaskTemplateData::getRow_sort)
                            .max(Integer::compareTo);
                    int maxRowSortForAdd = maxRowSort.orElse(-1);

                    findAndAddValues(_flow_no, json, _param_parent_key, inputParam, resultList, maxRowSortForAdd,inputList);

                } else {
                    resultList.add(inputParam);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }

    private void findAndAddValues(String _flow_no, JSONObject json, String param_parent_key, TbTaskTemplateData tbTaskTemplateData, List<TbTaskTemplateData> resultList, Integer maxRowSortForAdd, List<TbTaskTemplateData> inputList) {
        try {
            JSONArray jsonMap = json.getJSONArray(param_parent_key);

            if (jsonMap != null && jsonMap.size() > 0) {
                //获取当前lsit中的最大行,如果没有就默认是0

                Optional<Integer> maxRowSort = resultList.stream()
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .filter(entity -> entity.getParam_key().equals(tbTaskTemplateData.getParam_key()) && entity.getIs_Add() == 1) // 过滤出 param_key 等于 "your_param_key" 的元素
                        .map(TbTaskTemplateData::getRow_sort)
                        .max(Integer::compareTo);
                int maxRowSortValue = 0;

                if (maxRowSort.isPresent()) {
                    maxRowSortValue = maxRowSort.get() + 1;
                }

                Optional<Integer> maxRowSort2 = resultList.stream()
                        .filter(Objects::nonNull) // 过滤掉 null 值
                        .filter(entity -> entity.getParam_key().equals(tbTaskTemplateData.getParam_key()) && entity.getIs_Add() == 0) // 过滤出 param_key 等于 "your_param_key" 的元素
                        .map(TbTaskTemplateData::getRow_sort)
                        .max(Integer::compareTo);
                int maxRowSortValue2 = 0;

                if (maxRowSort2.isPresent()) {
                    maxRowSortValue2 = maxRowSort2.get() + 1;
                } else {
                    maxRowSortValue2 = maxRowSortForAdd + 1;
                }

                //int tempRow=0;

                for (int i = 0; i < jsonMap.size(); i++) {
                    JSONObject jsonObject = jsonMap.getJSONObject(i);

                    if (jsonObject != null) {
                        String value = jsonObject.getString(tbTaskTemplateData.getParam_key());

                        if (value.equals("[]")) {
                            value = "";
                        }
                        boolean IsNewRow = jsonObject.containsKey("row");
                        Integer row = tbTaskTemplateData.getRow_sort();

                        //传过来是单行的对象,实际上只要处理单行的就行,不然就会导致重复数据
                        //如果有Row 就代表是原来数据库里面有的值
                        TbTaskTemplateData newTbTaskTemplateData = new TbTaskTemplateData();
                        newTbTaskTemplateData.setFlow_no(tbTaskTemplateData.getFlow_no());
                        newTbTaskTemplateData.setFlow_level(tbTaskTemplateData.getFlow_level());
                        newTbTaskTemplateData.setVersion(tbTaskTemplateData.getVersion());
                        newTbTaskTemplateData.setTemplate_type(tbTaskTemplateData.getTemplate_type());
                        newTbTaskTemplateData.setParent_id(tbTaskTemplateData.getParent_id());
                        newTbTaskTemplateData.setParam_name(tbTaskTemplateData.getParam_name());
                        newTbTaskTemplateData.setParam_name_en(tbTaskTemplateData.getParam_name_en());
                        newTbTaskTemplateData.setParam_key(tbTaskTemplateData.getParam_key());
                        newTbTaskTemplateData.setParent_param_key(tbTaskTemplateData.getParent_param_key());
                        newTbTaskTemplateData.setParam_type(tbTaskTemplateData.getParam_type());
                        newTbTaskTemplateData.setLevel(tbTaskTemplateData.getLevel());
                        newTbTaskTemplateData.setSelect_level(tbTaskTemplateData.getSelect_level());
                        newTbTaskTemplateData.setParent_select_id(tbTaskTemplateData.getParent_select_id());
                        newTbTaskTemplateData.setTip(tbTaskTemplateData.getTip());
                        newTbTaskTemplateData.setRemark(tbTaskTemplateData.getRemark());
                        newTbTaskTemplateData.setSort(tbTaskTemplateData.getSort());
                        newTbTaskTemplateData.setIs_value(tbTaskTemplateData.getIs_value());

                        newTbTaskTemplateData.setRow_sort_old(tbTaskTemplateData.getRow_sort());
                        Integer _param_type = tbTaskTemplateData.getParam_type();

                        if (_param_type == 3 || _param_type == 4) {
                            if (value != null && !value.isEmpty()) {
                                List<String> keyList = new ArrayList<>();
                                //附件//图片
                                JSONArray valueList = jsonObject.getJSONArray(tbTaskTemplateData.getParam_key());
                                if (valueList != null && valueList.size() > 0) {
                                    for (int j = 0; j < valueList.size(); j++) {
                                        JSONObject valueObject = valueList.getJSONObject(j);
                                        if (valueObject != null) {
                                            if (valueObject.getString("param_key") == null) {
                                                String _param_key = String.valueOf(UUID.randomUUID());
                                                keyList.add(_param_key);
                                                TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                                tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                                tbKnowledgeBaseFile.setFlow_level(tbTaskTemplateData.getFlow_level());
                                                tbKnowledgeBaseFile.setParam_key(_param_key);

                                                String filename = valueObject.get("file_name") == null ? null : valueObject.get("file_name").toString();
                                                tbKnowledgeBaseFile.setFile_name(filename);
                                                tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                                tbKnowledgeBaseFile.setFile_relate_path(valueObject.get("picRelatePath") == null ? null : valueObject.get("picRelatePath").toString());
                                                tbKnowledgeBaseFile.setFile_type(_param_type);
                                                //valueObject.get("url") == null ? null : valueObject.get("url").toString()
                                                tbKnowledgeBaseFile.setUrl(valueObject.get("picRelatePath") == null ? null : valueObject.get("picRelatePath").toString());
                                                tbKnowledgeBaseFile.setSecret_key(valueObject.get("secretKey") == null ? null : valueObject.get("secretKey").toString());
                                                tbKnowledgeBaseFile.setFile_sid(valueObject.get("fileSid") == null ? null : valueObject.get("fileSid").toString());

                                                List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                                tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                                tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                            } else {
                                                keyList.add(valueObject.getString("param_key"));
                                            }
                                        }
                                    }

                                    if (keyList != null && keyList.size() > 0) {
                                        newTbTaskTemplateData.setParam_value(String.join(",", keyList));
                                    }
                                }
                            } else {
                                newTbTaskTemplateData.setParam_value(value);
                            }
                        }
                        //20251113 修改逻辑,前端传过来的值变成了文字,需要我自己去匹配出来key值
                        else if (_param_type == 2) {
                            String finalValue = value;
                            Optional<TbTaskTemplateData> optionalTbTaskTemplateData = inputList.stream()
                                    .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_name().equals(finalValue)&&tbTaskTemplateData2.getParent_param_key().equals(tbTaskTemplateData.getParam_key()))
                                    .findAny();

                            if (optionalTbTaskTemplateData.isPresent()) {
                                newTbTaskTemplateData.setParam_value(optionalTbTaskTemplateData.get().getParam_key());
                            } else {
                                newTbTaskTemplateData.setParam_value(value);
                            }
                        } else if (_param_type == 5) {
                            if (value!= null && value.startsWith("[")) {

                                ObjectMapper mapper = new ObjectMapper();
                                List<String> resultListMapper = mapper.readValue(value, List.class);
                                List<Object> resultList2 = new ArrayList<>();

                                for (String node : resultListMapper) {
                                    Optional<TbTaskTemplateData> optionalTbTaskTemplateData = inputList.stream()
                                            .filter(tbTaskTemplateData2 -> tbTaskTemplateData2.getParam_name().equals(node)&&tbTaskTemplateData2.getParent_param_key().equals(tbTaskTemplateData.getParam_key()))
                                            .findAny();

                                    if (optionalTbTaskTemplateData.isPresent()) {
                                        resultList2.add("\""+optionalTbTaskTemplateData.get().getParam_key()+"\"");
                                    }
                                }

                                newTbTaskTemplateData.setParam_value(resultList2.toString());
                            }
                        }
                        else {
                            newTbTaskTemplateData.setParam_value(value);
                        }

                        if (IsNewRow) {
                            Integer jsonRow = jsonObject.getInteger("row");

                            //去寻找自己的当前行
                            if (row != null && row == jsonRow) {
                                newTbTaskTemplateData.setRow_sort(maxRowSortValue);
                                newTbTaskTemplateData.setIs_Add(1);
                                resultList.add(newTbTaskTemplateData);
                                maxRowSortValue++;
                            } else {
                                continue;
                            }
                        }
                        //不然就是新增的行
                        else {
                            //判断一下是不是已经新增过了如果新增过了的话就不再新增了.
                            if (resultList != null && newTbTaskTemplateData != null) {
                                int finalMaxRowSortValue = maxRowSortValue2;
                                int finalMaxRowSortValue1 = maxRowSortValue;
                                int finalI = i;
                                boolean exists = resultList.stream()
                                        .anyMatch(entity -> entity.getParam_key().equals(tbTaskTemplateData.getParam_key()) && entity.getRow_sort() == finalI);
                                if (!exists) {
                                    newTbTaskTemplateData.setRow_sort(finalI);
                                    newTbTaskTemplateData.setIs_Add(0);
                                    resultList.add(newTbTaskTemplateData);
                                }
                            } else {
                                newTbTaskTemplateData.setRow_sort(i);
                                newTbTaskTemplateData.setIs_Add(0);
                                resultList.add(newTbTaskTemplateData);
                            }
                        }
                    }
                }
            }

            if (_flow_no == null || _flow_no.isEmpty()) {
                tbTaskTemplateData.setRow_sort(-1);
                resultList.add(tbTaskTemplateData);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void findAndAddValues2(Map<String, Object> jsonMap, String paramKey, String currentIndex, List<TbTaskTemplateData> resultList) {
        for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key.equals(paramKey)) {
                String valueStr = value == null ? "" : value.toString();
                //resultList.add(new TbTaskTemplateData(paramKey, valueStr, currentIndex));
            }
            if (value instanceof List) {
                List<Map<String, Object>> list = (List<Map<String, Object>>) value;
                for (int i = 0; i < list.size(); i++) {
                    String newIndex = currentIndex.isEmpty() ? String.valueOf(i) : currentIndex + "." + i;
                    findAndAddValues2(list.get(i), paramKey, newIndex, resultList);
                }
            } else if (value instanceof Map) {
                String newIndex = currentIndex.isEmpty() ? "" : currentIndex + ".";
                findAndAddValues2((Map<String, Object>) value, paramKey, newIndex, resultList);
            }
        }
    }

    // 空值转空字符串工具方法
    private static String nullToEmpty(String str) {
        return str == null ? "" : str;
    }

    private void sendMail(String flowType, String flowNo, Integer nowLevel) {
        //发送邮件
        try {
            //获取当前环节的处理人
            TbFlowProcessDetail param1 = new TbFlowProcessDetail();
            param1.setFlow_no(flowNo);
            param1.setFlow_type(flowType);
            param1.setFlow_level((nowLevel));
            List<TbFlowProcessDetail> tbFlowProcessDetailList1 = tbFlowProcessDetailDao.getFlowProcessDetail(param1);
            TbFlowProcessDetail tbFlowProcessDetail1 = new TbFlowProcessDetail();
            if (tbFlowProcessDetailList1 != null && tbFlowProcessDetailList1.size() > 0) {
                tbFlowProcessDetail1 = tbFlowProcessDetailList1.get(0);
            }
            String flowApprover1 = tbFlowProcessDetail1.getFlow_approver();

            Integer numflowApprover1 = 0;
            try {
                numflowApprover1 = Integer.parseInt(flowApprover1);
            } catch (Exception e) {

            }
            User u1 = userDao.getUserInfoById(numflowApprover1);

            String flowApproverName = "";
            if (u1 != null) {
                flowApproverName = u1.getDisplayName() + "/" + u1.getDomainAccount();
            }

            //去获取下一个节点的审核人信息
            TbFlowProcessDetail param2 = new TbFlowProcessDetail();
            param2.setFlow_no(flowNo);
            param2.setFlow_type(flowType);
            param2.setFlow_level((nowLevel + 1));

            List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
            if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                List<User> userList = new ArrayList<>();
                String flowApprover = tbFlowProcessDetail.getFlow_approver();

                Integer numflowApprover = 0;
                try {
                    numflowApprover = Integer.parseInt(flowApprover);
                } catch (Exception e) {

                }

                User u = userDao.getUserInfoById(numflowApprover);
                if (u != null) {
                    userList.add(u);
                }
                if (tbFlowProcessDetail.getCc() != null && !tbFlowProcessDetail.getCc().isEmpty()) {
                    Integer numflowApprover2 = 0;

                    try {
                        numflowApprover2 = Integer.parseInt(tbFlowProcessDetail.getCc());
                    } catch (Exception e) {

                    }

                    User u2 = userDao.getUserInfoById(numflowApprover2);
                    if (u2 != null) {
                        userList.add(u2);
                    }
                }

                List<MailAddress> mailAddressList = new ArrayList<>();
                for (User user : userList) {
                    if (user.getEmail().contains(",")) {
                        String[] emailsArr = user.getEmail().split(",");
                        for (String email : emailsArr) {
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(email);
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                            log.info("mailAddress: " + mailAddress);
                        }
                    } else {
                        MailAddress mailAddress = new MailAddress();
                        mailAddress.setMailAddress(user.getEmail());
                        mailAddress.setType(0);
                        mailAddressList.add(mailAddress);
                        log.info("mailAddress: " + mailAddress);
                    }
                }
                String flowUrl = "?flowNo=" + flowNo + "&type=edit&active=" + (nowLevel.intValue() + 1) + "";
                String mailContent = "";
                String title = "";
                String contenTitle = "";
                String vplWebUrl = knowledgeBaseFlowUrl + "/" + vplUrl;
                String deviceWebUrl = knowledgeBaseFlowUrl + "/" + deviceUrl;
                String designWebUrl = knowledgeBaseFlowUrl + "/" + designUrl;

                // 创建格式化器
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化当前时间
                String formattedDate = LocalDateTime.now().format(dtf);

                if (flowType.equals("vpl")) {
                    /*
                    * 【IDCM】待办: ****（第一环节人）提交的新器件vpl建库流程，流程单号:**，请尽快处理!
                        提交人（第一环节人）:***
                        达到时间: ***
                        当前环节: ****
                        新器件编码: ***
                        打开链接:点击打开
                    * */
                    //查询人员信息
                    //查询tbtask表
                    List<TbTaskVersion> tbTaskVersions = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                    TbTaskVersion tbTaskVersion = tbTaskVersions.get(0);

                    String webUrl = vplWebUrl + flowUrl;
                    title = "【IDCM】待办: " + flowApproverName + "提交的新器件vpl建库流程，流程单号:" + flowNo + "，请尽快处理!";
                    contenTitle = "【IDCM】待办: " + flowApproverName + "提交的新器件vpl建库流程，流程单号:" + flowNo + "，请尽快处理!";
                    mailContent = "<html><body>" +
                            "<p>提交人：" + flowApproverName + "</p>" +
                            "<p>达到时间：" + formattedDate + "</p>" +
                            "<p>当前环节：" + tbFlowProcessDetail.getFlow_name() + "</p>" +
                            "<p>新器件编码：" + tbTaskVersion.getComp_code() + "</p>" +
                            "<p>打开链接：" + "<a href='" + webUrl + "'>点击打开</a>" + "</p>" +
                            "</html></body>";
                }

                if (flowType.equals("device")) {
                    String webUrl = deviceWebUrl + flowUrl;
                    title = "【IDCM】待办: " + flowApproverName + "提交的新建维护器件工艺知识库流程，流程单号:" + flowNo + "，请尽快处理!";
                    contenTitle = "【IDCM】待办: " + flowApproverName + "提交的新建维护器件工艺知识库流程，流程单号:" + flowNo + "，请尽快处理!";
                    mailContent = "<html><body>" +
                            "<p>提交人：" + flowApproverName + "</p>" +
                            "<p>达到时间：" + formattedDate + "</p>" +
                            "<p>当前环节：" + tbFlowProcessDetail.getFlow_name() + "</p>" +
                            "<p>打开链接：" + "<a href='" + webUrl + "'>点击打开</a>" + "</p>" +
                            "</html></body>";
                }

                if (flowType.equals("design")) {
                    String webUrl = designWebUrl + flowUrl;
                    title = "【IDCM】待办: " + flowApproverName + "提交的新建维护工艺规范知识库流程，流程单号:" + flowNo + "，请尽快处理!";
                    contenTitle = "【IDCM】待办: " + flowApproverName + "提交的新建维护工艺规范知识库流程，流程单号:" + flowNo + "，请尽快处理!";
                    mailContent = "<html><body>" +
                            "<p>提交人：" + flowApproverName + "</p>" +
                            "<p>达到时间：" + formattedDate + "</p>" +
                            "<p>当前环节：" + tbFlowProcessDetail.getFlow_name() + "</p>" +
                            "<p>打开链接：" + "<a href='" + webUrl + "'>点击打开</a>" + "</p>" +
                            "</html></body>";
                }

                if (mailAddressList.size() > 0) {
                    Result result = thirdApiService.sendMail("", title, contenTitle,
                            mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
                    if (result.getCode() == 200) {
                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                        log.info(CommonUtils.formatCurrentTime() + "==========================================");
                        log.info("知识库邮件,发送成功");
                        System.out.println("知识库邮件,发送成功");
                    } else {
                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                        log.error(CommonUtils.formatCurrentTime() + "==========================================");
                        log.error("知识库邮件,发送失败:" + result.getMsgCn());
                        System.out.println("知识库邮件,发送失败:" + result.getMsgCn());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
            System.out.println("知识库邮件：" + e.getMessage());
        }
    }

    private void sendMail2(String flowType, String flowNo, Integer nowLevel) {
        //发送邮件
        try {
            //去获取下一个节点的审核人信息
            TbFlowProcessDetail param2 = new TbFlowProcessDetail();
            param2.setFlow_no(flowNo);
            param2.setFlow_type(flowType);
            param2.setFlow_level((nowLevel));

            List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
            if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                List<User> userList = new ArrayList<>();
                String flowApprover = tbFlowProcessDetail.getFlow_approver();

                Integer numflowApprover = 0;
                try {
                    numflowApprover = Integer.parseInt(flowApprover);
                } catch (Exception e) {

                }

                User u = userDao.getUserInfoById(numflowApprover);
                if (u != null) {
                    userList.add(u);
                }
                if (tbFlowProcessDetail.getCc() != null && !tbFlowProcessDetail.getCc().isEmpty()) {
                    Integer numflowApprover2 = 0;

                    try {
                        numflowApprover2 = Integer.parseInt(tbFlowProcessDetail.getCc());
                    } catch (Exception e) {

                    }

                    User u2 = userDao.getUserInfoById(numflowApprover2);
                    if (u2 != null) {
                        userList.add(u2);
                    }
                }

                List<MailAddress> mailAddressList = new ArrayList<>();
                for (User user : userList) {
                    if (user.getEmail().contains(",")) {
                        String[] emailsArr = user.getEmail().split(",");
                        for (String email : emailsArr) {
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(email);
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                            log.info("mailAddress: " + mailAddress);
                        }
                    } else {
                        MailAddress mailAddress = new MailAddress();
                        mailAddress.setMailAddress(user.getEmail());
                        mailAddress.setType(0);
                        mailAddressList.add(mailAddress);
                        log.info("mailAddress: " + mailAddress);
                    }
                }
                String flowUrl = "?flowNo=" + flowNo + "&type=edit&active=" + (nowLevel.intValue()) + "";
                String mailContent = "";
                String title = "";
                String contenTitle = "";
                String vplWebUrl = knowledgeBaseFlowUrl + "/" + vplUrl;
                // 创建格式化器
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                // 格式化当前时间
                String formattedDate = LocalDateTime.now().format(dtf);

                if (flowType.equals("vpl")) {
                    /*
                    * 【IDCM】待办: ****（第一环节人）提交的新器件vpl建库流程，流程单号:**，请尽快处理!
                        提交人（第一环节人）:***
                        达到时间: ***
                        当前环节: ****
                        新器件编码: ***
                        打开链接:点击打开
                    * */
                    //查询人员信息
                    //查询tbtask表
                    List<TbTaskVersion> tbTaskVersions = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                    TbTaskVersion tbTaskVersion = tbTaskVersions.get(0);

                    String webUrl = vplWebUrl + flowUrl;
                    title = "【IDCM】待办: 系统自动创建的新器件vpl建库流程，流程单号:" + flowNo + "，请尽快处理!";
                    contenTitle = title = "【IDCM】待办: 系统自动创建的新器件vpl建库流程，流程单号:" + flowNo + "，请尽快处理!";
                    mailContent = "<html><body>" +
                            "<p>达到时间：" + formattedDate + "</p>" +
                            "<p>当前环节：" + tbFlowProcessDetail.getFlow_name() + "</p>" +
                            "<p>新器件编码：" + tbTaskVersion.getComp_code() + "</p>" +
                            "<p>打开链接：" + "<a href='" + webUrl + "'>点击打开</a>" + "</p>" +
                            "</html></body>";
                }

                if (mailAddressList.size() > 0) {
                    Result result = thirdApiService.sendMail("", title, contenTitle,
                            mailContent, "10086", mailAddressList, null, null, null, null, 2, null);
                    if (result.getCode() == 200) {
                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                        log.info(CommonUtils.formatCurrentTime() + "==========================================");
                        log.info("知识库邮件,发送成功");
                        System.out.println("知识库邮件,发送成功");
                    } else {
                        System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                        log.error(CommonUtils.formatCurrentTime() + "==========================================");
                        log.error("知识库邮件,发送失败:" + result.getMsgCn());
                        System.out.println("知识库邮件,发送失败:" + result.getMsgCn());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
            System.out.println("知识库邮件：" + e.getMessage());
        }
    }

    @Override
    @Scheduled(cron = "0 0 * * * ?") // 每小时整点 执行一次检查是否要计算直通率
    public void scheduledCreateVplFlow() {
        TimerConfig timerConfigByType = timerConfigDao.getTimerConfigByType("ScheduledCreateVplFlow");
        if (timerConfigByType != null && timerConfigByType.getStatus() == 1) {
            LocalDateTime tmp = LocalDateTime.now();
            //保证是整点
            LocalDateTime now = tmp.withMinute(0).withSecond(0).withNano(0);
            System.out.println("[scheduledCreateVplFlow] 定时任务开始执行: " + CommonUtils.formatCurrentTime());

            try {
                PdmNewPartApplication param = new PdmNewPartApplication();
                //定时任务的处理逻辑
                //先查询PDM的数据

                Calendar calendar = Calendar.getInstance();
                Date endTime = calendar.getTime(); // 当前时间为结束时间

                calendar.add(Calendar.DAY_OF_MONTH, -3); // 回溯3天
                Date startTime = calendar.getTime();

                List<PdmNewPartApplication> listPdmNewPartApplication = pdmNewPartApplicationDao.getPdmNewPartApplicationList2(param, startTime, endTime);

                //查询现在数据库中已经建了流程的数据
                List<TbTaskVersion> tbTaskVersionList = tbTaskVersionDao.getAllTaskVersion();  //查询出来的就是需要去建流程的数据

                // 创建一个新的列表，用于存储剔除后的数据
                List<PdmNewPartApplication> newListPdmNewPartApplication = new ArrayList<>();

                for (PdmNewPartApplication pdmNewPartApplication1 : listPdmNewPartApplication) {
                    String compCode = pdmNewPartApplication1.getS1partnumber();
                    boolean exists = tbTaskVersionList.stream()
                            .filter(Objects::nonNull) // 过滤掉null值
                            .filter(version -> version.getComp_code() != null) // 过滤掉comp_code为空的元素
                            .anyMatch(version -> version.getComp_code().equals(compCode));
                    if (!exists) {
                        newListPdmNewPartApplication.add(pdmNewPartApplication1);
                    }
                }

                //拿到新的list以后,按照文档编号进行分组,查询出来有多少个编号信息
                Set<String> uniqueS1partnumbers = newListPdmNewPartApplication.stream()
                        .map(PdmNewPartApplication::getS1partnumber)
                        .collect(Collectors.toSet());

                List<Map<String, Object>> finalList = new ArrayList<>();

                List<Map<String, Object>> mailList = new ArrayList<>();

                for (String partNumber : uniqueS1partnumbers) {
                    Map<String, Object> tempMap = new HashMap<>();

                    List<PdmNewPartApplication> extractedFieldsList = newListPdmNewPartApplication.stream()
                            .filter(p -> partNumber.equals(p.getS1partnumber())) // 替换 "s1part" 为你的查询条件
                            .collect(Collectors.toList()); // 收集结果到一个新的列表

                    List<TbFlowCompVplPdm> listTbFlowCompVplPdm = new ArrayList<>();

                    if (!extractedFieldsList.isEmpty()) {
                        PdmNewPartApplication firstItem = extractedFieldsList.get(0);
                        TbFlowCompVplPdm convertedItem = new TbFlowCompVplPdm();

                        convertedItem.setDocumentName(firstItem.getDocumentName());
                        convertedItem.setS1PCBENCPFILENAME(firstItem.getS1PCBENCPFILENAME());
                        convertedItem.setS1partnumber(firstItem.getS1partnumber());
                        convertedItem.setS1partdescelements(firstItem.getS1partdescelements());
                        convertedItem.setH3productline(firstItem.getH3productline());
                        convertedItem.setH3product(firstItem.getH3product());

                        //20250808 新增逻辑,如果他都是为空的话,那么就直接去获取流程里面配置的默认人员,如果这个人没有查到信息,那也配置成默认人员
                        //查询默认配置人员
                        List<TbFlowDetail> detail1List = tbFlowDetailDao.getFolwListByType3("vpl", 1);
                        TbFlowDetail detail1 = new TbFlowDetail();
                        if (detail1List != null && detail1List.size() > 0) {
                            detail1 = detail1List.get(0);
                        }

                        List<TbFlowDetail> detail4List = tbFlowDetailDao.getFolwListByType3("vpl", 4);
                        TbFlowDetail detail4 = new TbFlowDetail();
                        if (detail4List != null && detail4List.size() > 0) {
                            detail4 = detail4List.get(0);
                        }

                        //处理一下人员信息,因为是字符串分隔的,所以需要拆分
                        //建库人员
                        if (firstItem.getEDA_JKR_Last_SPR() != null && !firstItem.getEDA_JKR_Last_SPR().isEmpty()) {
                            String[] split = firstItem.getEDA_JKR_Last_SPR().split(" ");
                            if (split != null && split.length > 0) {
                                if (split[1] != null && !split[1].isEmpty()) {
                                    List<String> List = Arrays.asList(split[1].split(","));

                                    List<User2> user2List = user2Dao.getUserInfoByCode(List);
                                    if (user2List != null && user2List.size() > 0) {
                                        convertedItem.setVpl_create_user(user2List.get(0).getUser_id());
                                        convertedItem.setVpl_create_user_info(user2List);
                                    } else {
                                        convertedItem.setVpl_create_user(detail1.getFlow_approver());
                                    }
                                }
                            }
                        } else {
                            if (detail1 != null) {
                                convertedItem.setVpl_create_user(detail1.getFlow_approver());
                            }
                        }

                        //工艺审核人员
                        if (firstItem.getGYSH_Last_SPR() != null && !firstItem.getGYSH_Last_SPR().isEmpty()) {
                            String[] split1 = firstItem.getGYSH_Last_SPR().split(" ");
                            if (split1 != null && split1.length > 0) {

                                if (split1[1] != null && !split1[1].isEmpty()) {
                                    List<String> List = Arrays.asList(split1[1].split(","));

                                    List<User2> user2List = user2Dao.getUserInfoByCode(List);
                                    if (user2List != null && user2List.size() > 0) {
                                        convertedItem.setDesigner(user2List.get(0).getUser_id());
                                        convertedItem.setDesigner_info(user2List);
                                    } else {
                                        convertedItem.setDesigner(detail4.getFlow_approver());
                                    }
                                }
                            }
                        } else {
                            if (detail4 != null) {
                                convertedItem.setDesigner(detail4.getFlow_approver());
                            }
                        }
                        listTbFlowCompVplPdm.add(convertedItem);
                    }
                    tempMap.put("compVplPdm", listTbFlowCompVplPdm);
                    if (listTbFlowCompVplPdm != null && listTbFlowCompVplPdm.size() > 0) {
                        tempMap.put("vpl_create_user", listTbFlowCompVplPdm.get(0).getVpl_create_user());
                        tempMap.put("vpl_create_user_info", listTbFlowCompVplPdm.get(0).getVpl_create_user_info());

                        tempMap.put("designer", listTbFlowCompVplPdm.get(0).getDesigner());
                        tempMap.put("designer_info", listTbFlowCompVplPdm.get(0).getDesigner_info());
                    }

                    List<TbFlowCompManufacturer> convertedList = extractedFieldsList.stream()
                            .map(item -> {
                                TbFlowCompManufacturer convertedItem = new TbFlowCompManufacturer();
                                convertedItem.setManufacturer(item.getManufacturer());
                                convertedItem.setManufacturer_type(item.getS1MANUPARTNUM());
                                convertedItem.setData_sources("PDM");
                                return convertedItem;
                            })
                            .collect(Collectors.toList());
                    tempMap.put("compManufacturer", convertedList);

                    //20250311添加数据来源字段
                    //tempMap.put("data_sources","PDM");

                    finalList.add(tempMap);
                }

                //循环处理最终list
                for (Map<String, Object> originalMap : finalList) {
                    //handleAdd("vpl",map,"deviceType");
                    JSONObject targetJson = new JSONObject(true); // 保持顺序
                    targetJson.put("type", "save");
                    targetJson.put("flow_no", "");
                    targetJson.put("flow_type", "vpl");
                    targetJson.put("flow_level", 1);
                    targetJson.put("description", new JSONArray());
                    targetJson.put("application", new JSONArray());
                    targetJson.put("knowledge_base_key", "");
                    targetJson.put("is_skip", 1);
                    // 构建flowInfo子对象
                    JSONObject flowInfo = new JSONObject();
                    flowInfo.put("designer", originalMap.get("designer"));
                    flowInfo.put("vpl_create_user", originalMap.get("vpl_create_user"));
                    flowInfo.put("comments", null);
                    flowInfo.put("flow_approver", originalMap.get("vpl_create_user"));
                    targetJson.put("flowInfo", flowInfo);

                    // 处理嵌套数组（保留原始结构）
                    targetJson.put("compManufacturer", originalMap.get("compManufacturer"));
                    targetJson.put("compVplPdm", originalMap.get("compVplPdm"));

                    // 初始化空数组字段
                    targetJson.put("compVpl", new JSONArray());
                    targetJson.put("compPkg", new JSONArray());
                    targetJson.put("compVplAttr", new JSONArray());
                    targetJson.put("compVplPinAttr", new JSONArray());

                    // 3. 输出格式化后的JSON
                    String finalJson = JSON.toJSONString(targetJson, true);

                    JSONObject jsonObject = JSONObject.parseObject(finalJson);

                    Result res = handleAdd("vpl", jsonObject, "deviceType", 1, "auto");

                    if (res.getCode() == 200) {

                        String _flow_no = res.getData().toString();

                        TbFlowProcessDetail updateFlowApper1 = new TbFlowProcessDetail();
                        updateFlowApper1.setUpdate_time(new Date());
                        updateFlowApper1.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper1.setFlow_no(_flow_no);
                        updateFlowApper1.setFlow_level(1);
                        updateFlowApper1.setFlow_approver(flowInfo.getString("vpl_create_user"));
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper1);

                        TbFlowProcessDetail updateFlowApper2 = new TbFlowProcessDetail();
                        updateFlowApper2.setUpdate_time(new Date());
                        updateFlowApper2.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper2.setFlow_no(_flow_no);
                        updateFlowApper2.setFlow_level(3);
                        updateFlowApper2.setFlow_approver(flowInfo.getString("vpl_create_user"));
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper2);

                        //如果是第一个节点的话,还要去更新一下主节点上面的当前审核人,其实不更新也行
                        TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                        tbFlowProcessMainDao.updateFlowProcessMainForAuthorize(flowInfo.getString("vpl_create_user"), _flow_no, 1);

                        TbFlowProcessDetail updateFlowApper3 = new TbFlowProcessDetail();
                        updateFlowApper3.setUpdate_time(new Date());
                        updateFlowApper3.setUpdate_user(UserHeaderHolder.getUserId());
                        updateFlowApper3.setFlow_no(_flow_no);
                        updateFlowApper3.setFlow_level(4);
                        updateFlowApper3.setFlow_approver(flowInfo.getString("designer"));
                        tbFlowProcessDetailDao.updateFlowProcessDetailApprover(updateFlowApper3);

                        sendMail2("vpl", _flow_no, 1);
                    }
                }
            } catch (Exception e) {
                // 记录日志或采取其他错误处理措施
                System.out.println("Error occurred scheduledCreateVplFlow: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            System.out.println("[ScheduledUpdatePkgName] 定时任务开关关闭状态，不需要执行: " + CommonUtils.formatCurrentTime());
        }
    }

    @Override
    @Scheduled(cron = "0 0 * * * ?") // 每小时整点 执行一次检查是否要计算直通率
    @Transactional(transactionManager = "MysqlTransactionManager7")
    public void scheduledSendDataToVpl() {
        TimerConfig timerConfigByType = timerConfigDao.getTimerConfigByType("ScheduledSendDataToVpl");
        if (timerConfigByType != null && timerConfigByType.getStatus() == 1) {
            LocalDateTime tmp = LocalDateTime.now();
            //保证是整点
            LocalDateTime now = tmp.withMinute(0).withSecond(0).withNano(0);
            System.out.println("[scheduledSendDataToVpl] 同步VPL定时任务开始执行: " + CommonUtils.formatCurrentTime());

            log.info("[scheduledSendDataToVpl] 同步VPL定时任务开始执行:", CommonUtils.formatCurrentTime());
            try {
                //首先查询出来所有待处理的任务信息
                List<TbFlowProcessMain> needSendToVpl = tbFlowProcessMainDao.getNeedSendToVpl();
                if (needSendToVpl != null && needSendToVpl.size() > 0) {
                    for (int i = 0; i < needSendToVpl.size(); i++) {
                        TbFlowProcessMain tbFlowProcessMain = needSendToVpl.get(i);
                        String flowNo = tbFlowProcessMain.getFlow_no();
                        //再去获取一下tbtaskversion的信息
                        List<TbTaskVersion> tbTaskVersions = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                        TbTaskVersion tbTaskVersion = tbTaskVersions.get(0);

                        if (tbTaskVersion.getComp_code() != null && !tbTaskVersion.getComp_code().isEmpty()) {
                            System.out.println("序号:" + i + ",器件编码:" + tbTaskVersion.getComp_code() + "" + CommonUtils.formatCurrentTime());

                            //将数据全部都查询出来
                            //封装信息 实际只会有一条
                            List<TbFlowCompPkg> tbFlowCompPkgs = tbFlowCompPkgDao.getTbFlowCompPkgByFlowNo(flowNo, 3);
                            List<TbFlowCompVplPinNumber> tbFlowCompVplPinNumbers = tbFlowCompVplPinNumberDao.getTbFlowCompVplPinNumberByFlowNo(flowNo, 3);
                            //器件信息 实际只会有一条
                            List<TbFlowCompVpl> tbFlowCompVpls = tbFlowCompVplDao.getTbFlowCompVplByFlowNo(flowNo, 4);
                            //器件属性信息 实际是可能多条数据
                            List<TbFlowCompVplAttr> tbFlowCompVplAttrs = tbFlowCompVplAttrDao.getTbFlowCompVplAttrByFlowNo(flowNo, 2);
                            //器件PDM信息 实际只会有一条
                            List<TbFlowCompVplPdm> tbFlowCompVplPdms = tbFlowCompVplPdmDao.getTbFlowCompVplPdmByFlowNo(flowNo, 1);
                            //器件引脚信息 实际是可能多条数据
                            List<TbFlowCompVplPinAttr> tbFlowCompVplPinAttrs = tbFlowCompVplPinAttrDao.getTbFlowCompVplPinAttrByFlowNo(flowNo, 2);
                            //厂家信息 实际是可能多条数据
                            List<TbFlowCompManufacturer> tbFlowCompManufacturers = tbFlowCompManufacturerDao.getTbFlowCompManufacturerByFlowNo(flowNo, 1);
                            //部分数据存在流程节点明细中了
                            TbFlowProcessDetail tbFlowProcessDetail = new TbFlowProcessDetail();
                            tbFlowProcessDetail.setFlow_no(flowNo);
                            tbFlowProcessDetail.setFlow_level(2);
                            List<TbFlowProcessDetail> tbFlowProcessDetails = tbFlowProcessDetailDao.getFlowProcessDetail(tbFlowProcessDetail);
                            TbFlowProcessDetail finalTbFlowProcessDetail = tbFlowProcessDetails.get(0);


                            OptionalDouble maxWeight = tbFlowCompVplAttrs.stream()
                                    .map(TbFlowCompVplAttr::getWeight)   // 提取 weight 字符串
                                    .mapToDouble(w -> {
                                        try {
                                            return Double.parseDouble(w);   // 字符串转数值
                                        } catch (NumberFormatException e) {
                                            return Double.NEGATIVE_INFINITY; // 无效值处理
                                        }
                                    })
                                    .max();  // 获取最大值
                            //1.Intf_From_VplWeb_Package
                            //2.Intf_From_VplWeb_Partdata
                            //3.Intf_From_VplWeb_Pinattr
                            //4.Intf_From_VplWeb_Pinnumber

                            //1.数据来源主体为TbFlowCompPkg和TbFlowCompVpl组合起来的信息
                            TbFlowCompPkg tbFlowCompPkg = tbFlowCompPkgs.get(0);
                            TbFlowCompVpl tbFlowCompVpl = tbFlowCompVpls.get(0);

                            IntfFromVplWebPackage intfFromVplWebPackage = new IntfFromVplWebPackage();
                            intfFromVplWebPackage.setGUID(UUID.randomUUID().toString().replaceAll("-", ""));

                            intfFromVplWebPackage.setPkg_name(convertNAToNull(tbFlowCompPkg.getPkg_name()));

                            intfFromVplWebPackage.setIs_size_not_fit(convertYesToNumber(tbFlowCompPkg.getIs_size_not_fit()));
                            intfFromVplWebPackage.setIs_grid_design(convertYesToNumber(tbFlowCompPkg.getIs_grid_design()));
                            intfFromVplWebPackage.setIs_special_design(convertYesToNumber(tbFlowCompPkg.getIs_special_design()));
                            intfFromVplWebPackage.setIs_small_air_gap(convertYesToNumber(tbFlowCompPkg.getIs_small_air_gap()));
                            intfFromVplWebPackage.setAssembly_type(convertNAToNull(tbFlowCompPkg.getAssembly_type()));
                            intfFromVplWebPackage.setFoot_num(convertNAToNull(tbFlowCompPkg.getFoot_num()));
                            intfFromVplWebPackage.setIs_dense_comp(convertYesToNumber(tbFlowCompVpl.getIs_dense_comp()));
                            intfFromVplWebPackage.setPastemask_thickness_min(convertNAToNull(tbFlowCompVpl.getPastemask_thickness_min()));
                            intfFromVplWebPackage.setPastemask_thickness_max(convertNAToNull(tbFlowCompVpl.getPastemask_thickness_max()));
                            intfFromVplWebPackage.setPin_min_pitch(convertNAToNull(tbFlowCompVpl.getPin_min_pitch()));
                            intfFromVplWebPackage.setBody_length(convertNAToNull(tbFlowCompPkg.getBody_length()));
                            intfFromVplWebPackage.setBody_width(convertNAToNull(tbFlowCompPkg.getBody_width()));
                            intfFromVplWebPackage.setPitch_o2c_x(convertNAToNull(tbFlowCompPkg.getPitch_o2c_x()));
                            intfFromVplWebPackage.setPitch_o2c_y(convertNAToNull(tbFlowCompPkg.getPitch_o2c_y()));
                            intfFromVplWebPackage.setPad_airgap_min(convertNAToNull(tbFlowCompPkg.getPad_airgap_min()));
                            //intfFromVplWebPackage.setCreator(user);

                            List<IntfFromVplWebPackage> intfFromVplWebPackages = new ArrayList<>();
                            if (intfFromVplWebPackage.getPkg_name() != null && !intfFromVplWebPackage.getPkg_name().isEmpty()) {
                                intfFromVplWebPackages.add(intfFromVplWebPackage);
                            }

                            if (tbFlowCompPkg.getIs_from_vpl() == null || !tbFlowCompPkg.getIs_from_vpl().equals("Y")) {

                                if (intfFromVplWebPackages != null && intfFromVplWebPackages.size() > 0) {
                                    log.info("[scheduledSendDataToVpl] 写入数据:", "同步封装信息");
                                    intfFromVplWebPackageDao.insertIntfFromVplWebPackageBatch(intfFromVplWebPackages);
                                }

                                List<IntfFromVplWebPinnumber> intfFromVplWebPinnumbers = new ArrayList<>();
                                //新增一个表需要同步
                                for (int c = 0; c < tbFlowCompVplPinNumbers.size(); c++) {
                                    TbFlowCompVplPinNumber tbFlowCompVplPinNumber = tbFlowCompVplPinNumbers.get(c);

                                    IntfFromVplWebPinnumber intfFromVplWebPinnumber = new IntfFromVplWebPinnumber();

                                    intfFromVplWebPinnumber.setGUID(UUID.randomUUID().toString().replaceAll("-", ""));
                                    intfFromVplWebPinnumber.setPkg_name(convertNAToNull(tbFlowCompVplPinNumber.getPkg_name()));
                                    intfFromVplWebPinnumber.setPad_name(convertNAToNull(tbFlowCompVplPinNumber.getPad_name()));
                                    intfFromVplWebPinnumber.setPin_number(convertNAToNull(tbFlowCompVplPinNumber.getPin_number()));
                                    intfFromVplWebPinnumber.setPin_x(convertNAToNull(tbFlowCompVplPinNumber.getPin_x()));
                                    intfFromVplWebPinnumber.setPin_y(convertNAToNull(tbFlowCompVplPinNumber.getPin_y()));
                                    intfFromVplWebPinnumber.setRegular_pad_length(convertNAToNull(tbFlowCompVplPinNumber.getRegular_pad_length()));
                                    intfFromVplWebPinnumber.setRegular_pad_width(convertNAToNull(tbFlowCompVplPinNumber.getRegular_pad_width()));
                                    intfFromVplWebPinnumber.setDrill_hole_length(convertNAToNull(tbFlowCompVplPinNumber.getDrill_hole_length()));
                                    intfFromVplWebPinnumber.setDrill_hole_width(convertNAToNull(tbFlowCompVplPinNumber.getDrill_hole_width()));
                                    intfFromVplWebPinnumber.setDrill_hole_tol_p(convertNAToNull(tbFlowCompVplPinNumber.getDrill_hole_tol_p()));
                                    intfFromVplWebPinnumber.setDrill_hole_tol_n(convertNAToNull(tbFlowCompVplPinNumber.getDrill_hole_tol_n()));
                                    intfFromVplWebPinnumber.setAnti_pad_size(convertNAToNull(tbFlowCompVplPinNumber.getAnti_pad_size()));
                                    intfFromVplWebPinnumber.setThermal_pad_size(convertNAToNull(tbFlowCompVplPinNumber.getThermal_pad_size()));
                                    //intfFromVplWebPinnumber.setCreator("creator值");

                                    intfFromVplWebPinnumbers.add(intfFromVplWebPinnumber);
                                }

                                if (intfFromVplWebPinnumbers.size() > 0) {
                                    final int batchSize = 10;
                                    for (int cc = 0; cc < intfFromVplWebPinnumbers.size(); cc += batchSize) {
                                        log.info("[scheduledSendDataToVpl] 写入数据:", "同步PinNumber信息" + cc);
                                        List<IntfFromVplWebPinnumber> subList = intfFromVplWebPinnumbers.subList(cc, Math.min(cc + batchSize, intfFromVplWebPinnumbers.size()));
                                        intfFromVplWebPinnumberDao.insertIntfFromVplWebPinnumberBatch(subList);
                                    }
                                    //intfFromVplWebPinnumberDao.insertIntfFromVplWebPinnumberBatch(intfFromVplWebPinnumbers);
                                } else {
                                    log.info("[scheduledSendDataToVpl] 写入数据:", "没有需要同步的PinNumber信息");
                                }
                            }

                            List<IntfFromVplWebPartdata> intfFromVplWebPartdatas = new ArrayList<>();
                            //2.数据来源主体为TbFlowCompVplAttr和tbFlowCompVplAttrs组合起来的信息
                            //增加处理情况
                            if (tbFlowCompVplAttrs != null && tbFlowCompVplAttrs.size() > 0) {
                                for (int a = 0; a < tbFlowCompVplAttrs.size(); a++) {
                                    TbFlowCompVplAttr tbFlowCompVplAttr = tbFlowCompVplAttrs.get(a);

                                    //要通过厂家型号去查询到TbFlowCompManufacturer的数据信息
                                    Optional<TbFlowCompManufacturer> firstAManufacturer = tbFlowCompManufacturers.stream()
                                            .filter(m -> tbFlowCompVplAttr.getManufacturer_type().equals(m.getManufacturer_type()))  // 过滤条件[7,8](@ref)
                                            .findFirst();  // 获取首个匹配元素[6](@ref)

                                    IntfFromVplWebPartdata intfFromVplWebPartdata = new IntfFromVplWebPartdata();

                                    intfFromVplWebPartdata.setGUID(UUID.randomUUID().toString().replaceAll("-", ""));
                                    intfFromVplWebPartdata.setCode(tbFlowCompVpl.getComp_code());
                                    intfFromVplWebPartdata.setMcode(convertNAToNull(tbFlowCompVplAttr.getMcode()));
                                    intfFromVplWebPartdata.setMpn(convertNAToNull(tbFlowCompVplAttr.getMpn()));
                                    intfFromVplWebPartdata.setManufacturer_type(convertNAToNull(tbFlowCompVplAttr.getManufacturer_type()));
                                    //intfFromVplWebPartdata.setComp_type("comp_type");

                                    intfFromVplWebPartdata.setPkg_name(convertNAToNull(tbFlowCompPkg.getPkg_name()));//convertNAToNull(tbFlowCompVplAttr.getPkg_name())
                                    intfFromVplWebPartdata.setCoplanarity(convertNAToNull(tbFlowCompVplAttr.getCoplanarity()));
                                    intfFromVplWebPartdata.setWeight(convertNAToNull(tbFlowCompVplAttr.getWeight()));
                                    intfFromVplWebPartdata.setAssembly_type(convertNAToNull(tbFlowCompVplAttr.getAssembly_type()));
                                    intfFromVplWebPartdata.setBody_length(convertNAToNull(tbFlowCompVplAttr.getBody_length()));
                                    intfFromVplWebPartdata.setBody_length_tol_p(convertNAToNull(tbFlowCompVplAttr.getBody_length_tol_p()));
                                    intfFromVplWebPartdata.setBody_length_tol_n(convertNAToNull(tbFlowCompVplAttr.getBody_length_tol_n()));
                                    intfFromVplWebPartdata.setBody_width(convertNAToNull(tbFlowCompVplAttr.getBody_width()));
                                    intfFromVplWebPartdata.setBody_width_tol_p(convertNAToNull(tbFlowCompVplAttr.getBody_width_tol_p()));
                                    intfFromVplWebPartdata.setBody_width_tol_n(convertNAToNull(tbFlowCompVplAttr.getBody_width_tol_n()));
                                    intfFromVplWebPartdata.setBody_height(convertNAToNull(tbFlowCompVplAttr.getBody_height()));
                                    intfFromVplWebPartdata.setBody_height_tol_p(convertNAToNull(tbFlowCompVplAttr.getBody_height_tol_p()));
                                    intfFromVplWebPartdata.setBody_height_tol_n(convertNAToNull(tbFlowCompVplAttr.getBody_height_tol_n()));
                                    intfFromVplWebPartdata.setStandoff(convertNAToNull(tbFlowCompVplAttr.getStandoff()));
                                    intfFromVplWebPartdata.setPth_diameter_min(convertNAToNull(tbFlowCompVplAttr.getPth_diameter_min()));

                                    if (firstAManufacturer.isPresent()) {
                                        TbFlowCompManufacturer target = firstAManufacturer.get();
                                        intfFromVplWebPartdata.setManufacturer(convertNAToNull(target.getManufacturer()));
                                        intfFromVplWebPartdata.setBoard_thickness_min(convertNAToNull(target.getBoard_thickness_min()));
                                        intfFromVplWebPartdata.setBoard_thickness_max(convertNAToNull(target.getBoard_thickness_max()));
                                        intfFromVplWebPartdata.setIs_secd_reflow_drop(convertNAToNull(convertYesToNumber(target.getIs_secd_reflow_drop())));
                                        intfFromVplWebPartdata.setBga_height_min(convertNAToNull(target.getBga_height_min()));
                                        intfFromVplWebPartdata.setSolder_tg_max(convertNAToNull(target.getSolder_tg_max()));
                                        intfFromVplWebPartdata.setUnbd_thickness_min(convertNAToNull(target.getUnbd_thickness_min()));

                                    }
                                    //intfFromVplWebPartdata.setIs_sensitive("is_sensitive");
                                    intfFromVplWebPartdata.setOrientation(convertYesToNumber(tbFlowCompVplAttr.getIs_orientation()));
                                    intfFromVplWebPartdata.setIs_glue(convertYesToNumber(tbFlowCompVpl.getIs_glue()));
                                    //intfFromVplWebPartdata.setComponent_high_max(target.getcomp);

                                    if (maxWeight.isPresent() && maxWeight.getAsDouble() != Double.NEGATIVE_INFINITY) {
                                        intfFromVplWebPartdata.setWeight_max(String.valueOf(maxWeight.getAsDouble()));
                                    }

                                    intfFromVplWebPartdata.setHigh_max_vpl(convertNAToNull(finalTbFlowProcessDetail.getMax_Body_height()));
                                    intfFromVplWebPartdata.setPin_high_min(convertNAToNull(finalTbFlowProcessDetail.getMin_Pin_length()));
                                    intfFromVplWebPartdata.setPin_high_max(convertNAToNull(finalTbFlowProcessDetail.getMax_Pin_length()));
                                    intfFromVplWebPartdata.setIs_tht_power(convertYesToNumber(tbFlowCompVpl.getIs_tht_power()));
                                    intfFromVplWebPartdata.setIs_tht_capacitor(convertYesToNumber(tbFlowCompVpl.getIs_tht_capcitor()));
                                    intfFromVplWebPartdata.setIs_little_retentionforce(convertYesToNumber(tbFlowCompVpl.getIs_little_retentionforce()));
                                    intfFromVplWebPartdata.setCreate_time(new Date());

                                    if(intfFromVplWebPartdata.getCode()!=null&&!intfFromVplWebPartdata.getCode().isEmpty())
                                    {
                                        intfFromVplWebPartdatas.add(intfFromVplWebPartdata);
                                    }

                                }
                            } else {
                                //这种情况就是没有上传附件信息的时候,也需要把数据回传过去
                                for (int b = 0; b < tbFlowCompManufacturers.size(); b++) {
                                    TbFlowCompManufacturer target = tbFlowCompManufacturers.get(b);

                                    IntfFromVplWebPartdata intfFromVplWebPartdata = new IntfFromVplWebPartdata();
                                    intfFromVplWebPartdata.setGUID(UUID.randomUUID().toString().replaceAll("-", ""));
                                    intfFromVplWebPartdata.setCode(target.getComp_code());
                                    intfFromVplWebPartdata.setManufacturer(convertNAToNull(target.getManufacturer()));
                                    intfFromVplWebPartdata.setManufacturer_type(convertNAToNull(target.getManufacturer_type()));
                                    intfFromVplWebPartdata.setBoard_thickness_min(convertNAToNull(target.getBoard_thickness_min()));
                                    intfFromVplWebPartdata.setBoard_thickness_max(convertNAToNull(target.getBoard_thickness_max()));
                                    intfFromVplWebPartdata.setIs_secd_reflow_drop(convertNAToNull(convertYesToNumber(target.getIs_secd_reflow_drop())));
                                    intfFromVplWebPartdata.setBga_height_min(convertNAToNull(target.getBga_height_min()));
                                    intfFromVplWebPartdata.setSolder_tg_max(convertNAToNull(target.getSolder_tg_max()));
                                    intfFromVplWebPartdata.setUnbd_thickness_min(convertNAToNull(target.getUnbd_thickness_min()));
                                    intfFromVplWebPartdata.setPkg_name(convertNAToNull(tbFlowCompPkg.getPkg_name()));
                                    intfFromVplWebPartdata.setIs_glue(convertYesToNumber(tbFlowCompVpl.getIs_glue()));
                                    intfFromVplWebPartdata.setIs_tht_power(convertYesToNumber(tbFlowCompVpl.getIs_tht_power()));
                                    intfFromVplWebPartdata.setIs_tht_capacitor(convertYesToNumber(tbFlowCompVpl.getIs_tht_capcitor()));
                                    intfFromVplWebPartdata.setIs_little_retentionforce(convertYesToNumber(tbFlowCompVpl.getIs_little_retentionforce()));
                                    intfFromVplWebPartdata.setCreate_time(new Date());

                                    if(intfFromVplWebPartdata.getCode()!=null&&!intfFromVplWebPartdata.getCode().isEmpty())
                                    {
                                        intfFromVplWebPartdatas.add(intfFromVplWebPartdata);
                                    }
                                }
                            }


                            if (intfFromVplWebPartdatas.size() > 0) {
                                log.info("[scheduledSendDataToVpl] 写入数据:", "同步Partdata信息");
                                intfFromVplWebPartdataDao.insertIntfFromVplWebPartdataBatch(intfFromVplWebPartdatas);
                            } else {
                                log.info("[scheduledSendDataToVpl] 写入数据:", "没有需要同步的Partdata信息");
                            }

                            //3.数据来源主体为TbFlowCompVplPinAttr
                            //4.数据来源主体为TbFlowCompVplPinAttr

                            List<IntfFromVplWebPinattr> intfFromVplWebPinattrs = new ArrayList<>();


                            for (int b = 0; b < tbFlowCompVplPinAttrs.size(); b++) {
                                TbFlowCompVplPinAttr tbFlowCompVplPinAttr = tbFlowCompVplPinAttrs.get(b);

                                IntfFromVplWebPinattr intfFromVplWebPinattr = new IntfFromVplWebPinattr();
                                // 设置属性值
                                intfFromVplWebPinattr.setGUID(UUID.randomUUID().toString().replaceAll("-", ""));
                                intfFromVplWebPinattr.setMpn(convertNAToNull(tbFlowCompVplPinAttr.getMpn()));
                                intfFromVplWebPinattr.setPin_min_pitch(convertNAToNull(tbFlowCompVplPinAttr.getPin_min_pitch()));
                                intfFromVplWebPinattr.setPin_count(convertNAToNull(tbFlowCompVplPinAttr.getPin_count()));
                                intfFromVplWebPinattr.setPin_number(convertNAToNull(tbFlowCompVplPinAttr.getPin_number()));
                                intfFromVplWebPinattr.setPin_x_v(convertNAToNull(tbFlowCompVplPinAttr.getPin_x_v()));
                                intfFromVplWebPinattr.setPin_y_v(convertNAToNull(tbFlowCompVplPinAttr.getPin_y_v()));
                                intfFromVplWebPinattr.setPin_length(convertNAToNull(tbFlowCompVplPinAttr.getPin_length()));
                                intfFromVplWebPinattr.setPin_width(convertNAToNull(tbFlowCompVplPinAttr.getPin_width()));
                                intfFromVplWebPinattr.setPin_length_tol_p(convertNAToNull(tbFlowCompVplPinAttr.getPin_length_tol_p()));
                                intfFromVplWebPinattr.setPin_length_tol_n(convertNAToNull(tbFlowCompVplPinAttr.getPin_length_tol_n()));
                                intfFromVplWebPinattr.setPin_width_tol_p(convertNAToNull(tbFlowCompVplPinAttr.getPin_width_tol_p()));
                                intfFromVplWebPinattr.setPin_width_tol_n(convertNAToNull(tbFlowCompVplPinAttr.getPin_width_tol_n()));
                                intfFromVplWebPinattr.setPin_type(convertNAToNull(tbFlowCompVplPinAttr.getPin_type()));
                                intfFromVplWebPinattr.setPin_high(convertNAToNull(tbFlowCompVplPinAttr.getPin_high()));
                                intfFromVplWebPinattr.setPin_high_tol_p(convertNAToNull(tbFlowCompVplPinAttr.getPin_high_tol_p()));
                                intfFromVplWebPinattr.setPin_high_tol_n(convertNAToNull(tbFlowCompVplPinAttr.getPin_high_tol_n()));
                                // intfFromVplWebPinattr.setCreator("creator值");
                                intfFromVplWebPinattrs.add(intfFromVplWebPinattr);
                            }

                            if (intfFromVplWebPinattrs.size() > 0) {
                                final int batchSize = 10;
                                for (int cc = 0; cc < intfFromVplWebPinattrs.size(); cc += batchSize) {
                                    log.info("[scheduledSendDataToVpl] 写入数据:", "同步Pinattrs信息" + cc);
                                    List<IntfFromVplWebPinattr> subList = intfFromVplWebPinattrs.subList(cc, Math.min(cc + batchSize, intfFromVplWebPinattrs.size()));
                                    intfFromVplWebPinattrDao.insertIntfFromVplWebPinattrBatch(subList);
                                }
                                //intfFromVplWebPinattrDao.insertIntfFromVplWebPinattrBatch(intfFromVplWebPinattrs);
                                //intfFromVplWebPinnumberDao.insertIntfFromVplWebPinnumberBatch(intfFromVplWebPinnumbers);
                            } else {
                                log.info("[scheduledSendDataToVpl] 写入数据:", "没有需要同步的Pinattrs信息");
                            }

                            //更新状态为Y

                            tbFlowProcessMainDao.isSendToVpl(flowNo);
                        }
                    }
                }
            } catch (Exception e) {
                // 记录日志或采取其他错误处理措施
                System.out.println("Error occurred scheduledSendDataToVpl: " + e.getMessage());
                log.info("Error occurred scheduledSendDataToVpl:", e.getMessage());
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } else {
            System.out.println("[ScheduledSendDataToVpl] 定时任务开关关闭状态，不需要执行: " + CommonUtils.formatCurrentTime());
        }

    }

    public static String convertYesToNumber(String input) {
        if (input == null) return "0";

        if ("是".equals(input)) {          // 核心逻辑：中文"是"转1
            return "1";
        } else if ("0".equals(input) || "1".equals(input)) {  // 直接返回0/1字符串
            return input;
        } else {
            try {
                double num = Double.parseDouble(input.trim());  // 处理数字类型输入
                return (num == 0 || num == 1) ? String.valueOf((int) num) : "0";
            } catch (NumberFormatException e) {  // 非数字类型直接返回0
                return "0";
            }
        }
    }

    private String convertNAToNull(String value) {
        if (value == null || value.isEmpty() || "N/A".equalsIgnoreCase(value)) {
            return null;
        }
        return value;
    }

    @Override
    @Scheduled(cron = "0 0 7 * * ?") // 每天凌晨7点执行 刷新封装信息
    @Transactional(transactionManager = "MysqlTransactionManager7")
    public void scheduledUpdatePkgName() {

        TimerConfig timerConfigByType = timerConfigDao.getTimerConfigByType("ScheduledUpdatePkgName");

        if (timerConfigByType != null && timerConfigByType.getStatus() == 1) {

            LocalDateTime tmp = LocalDateTime.now();
            //保证是整点
            LocalDateTime now = tmp.withMinute(0).withSecond(0).withNano(0);
            System.out.println("[scheduledUpdatePkgName] 定时刷新器件编码对应的封装名: " + CommonUtils.formatCurrentTime());

            log.info("[scheduledUpdatePkgName] 定时刷新器件编码对应的封装名:", CommonUtils.formatCurrentTime());
            try {
                //首先查询出来所有器件编码的不为空的知识数据
                List<TbKnowledgeBaseData> tbKnowledgeBaseDataList = tbKnowledgeBaseDataDao.getAllByParamName("器件编码");

                if (tbKnowledgeBaseDataList != null && tbKnowledgeBaseDataList.size() > 0) {
                    //查询封装信息
                    List<PdmPartPackageInfo> pppiList = pdmPartPackageInfoDao.getPdmPartPackageInfoList();

                    if (pppiList != null && pppiList.size() > 0) {
                        Map<String, String> packageMap = pppiList.stream()
                                .filter(Objects::nonNull) // 防null处理
                                .collect(Collectors.toMap(
                                        PdmPartPackageInfo::getS1partnumber,
                                        PdmPartPackageInfo::getS1PCBENCPFILENAME,
                                        (existing, replacement) -> existing // 重复键取第一个值
                                ));

                        for (TbKnowledgeBaseData tbKnowledgeBaseData : tbKnowledgeBaseDataList) {
                            String componentCode = tbKnowledgeBaseData.getParam_value();
                            String componentPackage = packageMap.get(componentCode);

                            if (componentPackage != null) {
                                // 更新数据库
                                tbKnowledgeBaseDataDao.updatePkgName(tbKnowledgeBaseData.getKnowledge_base_key(), "器件封装", componentPackage);
                            }
                        }
                    }
                }

            } catch (Exception e) {
                // 记录日志或采取其他错误处理措施
                System.out.println("Error occurred scheduledUpdatePkgName: " + e.getMessage());
                log.info("Error occurred scheduledUpdatePkgName:", e.getMessage());
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } else {
            System.out.println("[ScheduledUpdatePkgName] 定时任务开关关闭状态，不需要执行: " + CommonUtils.formatCurrentTime());
        }

    }

    @Override
    @Scheduled(cron = "0 0 * * * ?") // 每小时整点
    //@Scheduled(fixedRate = 1000 * 3600 * 3)
    public void scheduleKnowledgeBaseEmail() {

        TimerConfig timerConfigByType = timerConfigDao.getTimerConfigByType("scheduleKnowledgeBaseEmail");

        if (timerConfigByType != null && timerConfigByType.getStatus() == 1) {

            boolean isRun = false;
            LocalDateTime tmp = LocalDateTime.now();
            //保证是整点
            LocalDateTime now = tmp.withMinute(0).withSecond(0).withNano(0);

            // 获取当前小时数（24小时制）
            int hour = now.getHour(); // [1,2,3](@ref)

            // 根据不同时段执行相应代码
            if (hour == 8) {
                isRun = true;
            } else if (hour == 16) {
                isRun = true;
            } else {
                isRun = false;
            }
            //isRun = true;
            if (isRun) {
                System.out.println("[scheduleKnowledgeBaseEmail] 超时任务处理: " + CommonUtils.formatCurrentTime());
                try {
                    List<TbFlowProcessMain> tbFlowProcessMainList = tbFlowProcessMainDao.getFlowProcessMainByStatus();

                    if (tbFlowProcessMainList != null && tbFlowProcessMainList.size() > 0) {
                        List<TbFlowProcessMain> resultList = new ArrayList<>();
                        Calendar calendar = Calendar.getInstance();
                        // 获取当前时间减去24小时的时间点
                        calendar.add(Calendar.HOUR, -24);
                        Date twentyFourHoursAgo = calendar.getTime();

                        //添加一个逻辑,去判断当天是否有过记录了。没有的话才写进去.
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                        // 格式化日期
                        String formattedDate1 = tmp.format(formatter);

                        for (TbFlowProcessMain process : tbFlowProcessMainList) {
                            Date referenceTime;
                            // 如果 updateTime 为空，使用 createTime；否则使用 updateTime
                            if (process.getUpdate_time() == null) {
                                referenceTime = process.getCreate_time();
                            } else {
                                referenceTime = process.getUpdate_time();
                            }
                            List<EmailReminder> erList=emailReminderDao.getEmailReminderByCorrelationId("knowledge_base_"+process.getFlow_type(), process.getId(),formattedDate1);
                            if(erList!=null&&erList.size()>0)
                            {
                                //预留时间格式
                            }
                            else
                            {
                                // 检查时间是否超过24小时
                                if (referenceTime != null && referenceTime.before(twentyFourHoursAgo)) {
                                    resultList.add(process);
                                }
                            }
                        }

                        for (TbFlowProcessMain tfpm : resultList) {
                            String flowNo = tfpm.getFlow_no();
                            String flowType = tfpm.getFlow_type();
                            Integer nowLevel = tfpm.getNow_level();

                            TbFlowProcessDetail param2 = new TbFlowProcessDetail();
                            param2.setFlow_no(flowNo);
                            param2.setFlow_type(flowType);
                            param2.setFlow_level(nowLevel);

                            List<TbFlowProcessDetail> tbFlowProcessDetailList = tbFlowProcessDetailDao.getFlowProcessDetail(param2);
                            if (tbFlowProcessDetailList != null && tbFlowProcessDetailList.size() > 0) {
                                TbFlowProcessDetail tbFlowProcessDetail = tbFlowProcessDetailList.get(0);

                                List<User> userList = new ArrayList<>();
                                String flowApprover = tbFlowProcessDetail.getFlow_approver();

                                Integer numflowApprover = 0;
                                try {
                                    numflowApprover = Integer.parseInt(flowApprover);
                                } catch (Exception e) {

                                }
                                String flowApproverName = "";
                                User u = userDao.getUserInfoById(numflowApprover);
                                if (u != null) {
                                    userList.add(u);
                                    flowApproverName = u.getDisplayName() + "/" + u.getDomainAccount();
                                }
                                if (tbFlowProcessDetail.getCc() != null && !tbFlowProcessDetail.getCc().isEmpty()) {
                                    Integer numflowApprover2 = 0;

                                    try {
                                        numflowApprover2 = Integer.parseInt(tbFlowProcessDetail.getCc());
                                    } catch (Exception e) {

                                    }

                                    User u2 = userDao.getUserInfoById(numflowApprover2);
                                    if (u2 != null) {
                                        userList.add(u2);
                                    }
                                }

                                List<MailAddress> mailAddressList = new ArrayList<>();
                                for (User user : userList) {
                                    if (user.getEmail().contains(",")) {
                                        String[] emailsArr = user.getEmail().split(",");
                                        for (String email : emailsArr) {
                                            MailAddress mailAddress = new MailAddress();
                                            mailAddress.setMailAddress(email);
                                            mailAddress.setType(0);
                                            mailAddressList.add(mailAddress);
                                            log.info("mailAddress: " + mailAddress);
                                        }
                                    } else {
                                        MailAddress mailAddress = new MailAddress();
                                        mailAddress.setMailAddress(user.getEmail());
                                        mailAddress.setType(0);
                                        mailAddressList.add(mailAddress);
                                        log.info("mailAddress: " + mailAddress);
                                    }
                                }
                                String flowUrl = "?flowNo=" + flowNo + "&type=edit&active=" + (nowLevel.intValue() + 1) + "";
                                String mailContent = "";
                                String title = "";
                                String contenTitle = "";
                                String vplWebUrl = knowledgeBaseFlowUrl + "/" + vplUrl;
                                String deviceWebUrl = knowledgeBaseFlowUrl + "/" + deviceUrl;
                                String designWebUrl = knowledgeBaseFlowUrl + "/" + designUrl;

                                // 创建格式化器
                                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                // 格式化当前时间
                                String formattedDate = LocalDateTime.now().format(dtf);
                                String typeName = "知识库任务超时未处理";
                                SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                String formattedCreateTime = "";
                                if (tfpm.getCreate_time() != null) {
                                    formattedCreateTime = dateFormatter.format(tfpm.getCreate_time());
                                }
                                String formattedUpdateTime = "";
                                if (tfpm.getUpdate_time() != null) {
                                    formattedUpdateTime = dateFormatter.format(tfpm.getUpdate_time());
                                }
                                if (flowType.equals("vpl")) {

                                    List<TbTaskVersion> tbTaskVersions = tbTaskVersionDao.getTaskVersionByFlowNo(flowNo);
                                    TbTaskVersion tbTaskVersion = tbTaskVersions.get(0);

                                    String webUrl = vplWebUrl + flowUrl;
                                    //mailContent = "<p>【IDCM】待办: 需要您处理的新器件vpl建库流程已超时24小时，流程单号:" + flowNo + "，请尽快处理!</p>" +
                                    //        "<p>任务创建时间：" + tfpm.getCreate_time() + "</p>" +
                                    //        "<p>任务到达时间：" + tfpm.getUpdate_time() + "</p>" +
                                    //        "<p>当前环节：" + tbFlowProcessDetail.getFlow_name() + "</p>" +
                                    //        "<p>新器件编码：" + tbTaskVersion.getComp_code() + "</p>" +
                                    //        "<p>打开链接：" + "<a href='" + webUrl + "'>点击打开</a>" + "</p>";
                                    JSONObject mailContentJO = new JSONObject(new LinkedHashMap<>());
                                    mailContentJO.put("新器件编码",tbTaskVersion.getComp_code());
                                    mailContentJO.put("任务创建时间",formattedCreateTime);
                                    mailContentJO.put("任务到达时间",formattedUpdateTime);
                                    mailContentJO.put("当前环节",tbFlowProcessDetail.getFlow_name());
                                    mailContentJO.put("链接","<a href='" + webUrl + "'>点击打开</a>");

                                    mailContent = mailContentJO.toJSONString();

                                }

                                if (flowType.equals("device")) {
                                    typeName = "新建维护器件工艺知识库";
                                    String webUrl = deviceWebUrl + flowUrl;

                                    JSONObject mailContentJO = new JSONObject(new LinkedHashMap<>());
                                    mailContentJO.put("新器件编码","");
                                    mailContentJO.put("任务创建时间",formattedCreateTime);
                                    mailContentJO.put("任务到达时间",formattedUpdateTime);
                                    mailContentJO.put("当前环节",tbFlowProcessDetail.getFlow_name());
                                    mailContentJO.put("链接","<a href='" + webUrl + "'>点击打开</a>");

                                    mailContent = mailContentJO.toJSONString();
                                }

                                if (flowType.equals("design")) {
                                    typeName = "新建维护工艺规范知识库";
                                    String webUrl = designWebUrl + flowUrl;

                                    JSONObject mailContentJO = new JSONObject(new LinkedHashMap<>());
                                    mailContentJO.put("新器件编码","");
                                    mailContentJO.put("任务创建时间",formattedCreateTime);
                                    mailContentJO.put("任务到达时间",formattedUpdateTime);
                                    mailContentJO.put("当前环节",tbFlowProcessDetail.getFlow_name());
                                    mailContentJO.put("链接","<a href='" + webUrl + "'>点击打开</a>");

                                    mailContent = mailContentJO.toJSONString();
                                }

                                if (mailAddressList.size() > 0) {
                                    EmailReminder er = new EmailReminder();
                                    er.setMail_type("knowledge_base_" + flowType);
                                    er.setMail_type_name(typeName);
                                    er.setTitle(title);
                                    er.setMail_content_title(contenTitle);
                                    er.setMail_content(mailContent);
                                    String result = mailAddressList.stream()
                                            .map(MailAddress::getMailAddress)
                                            .collect(Collectors.joining(","));
                                    er.setMail_address_list(result);
                                    er.setCorrelation_id(tfpm.getId());
                                    er.setCreate_time(new Date());
                                    er.setStatus(0);
                                    
                                    List<EmailReminder> erList = new ArrayList<>();
                                    erList.add(er);

                                    emailReminderDao.insertEmailReminderBatch(erList);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    // 记录日志或采取其他错误处理措施
                    System.out.println("Error occurred scheduleKnowledgeBaseEmail: " + e.getMessage());
                    log.info("Error occurred scheduleKnowledgeBaseEmail:", e.getMessage());
                    e.printStackTrace();
                }
            }

        } else {
            System.out.println("[scheduleKnowledgeBaseEmail] 定时任务开关关闭状态，不需要执行: " + CommonUtils.formatCurrentTime());
        }

    }


    public Result vplSkipNode4(String data, String _flow_no, JSONObject jsonObject, String _type, String _flow_type, Boolean is_need_knowledge_base) {
        try {
            //解析Json字符串
            //判断是否为空
            if (data != null && !data.isEmpty()) {
                //先过第四个节点,然后再手动过一下第五个节点信息
                //operateTaskFlow(data);
                Result first4 = handleUpdateAndCommit(_flow_no, jsonObject, _type, _flow_type, is_need_knowledge_base, false, true, "Y");

                if (first4.getCode() == 200) {
                    JSONObject jsonObject2 = JSONObject.parseObject(data);
                    String _flow_no2 = jsonObject.getString("flow_no");
                    String _knowledge_base_key2 = jsonObject.getString("knowledge_base_key");
                    Integer _is_need_knowledge_base2 = jsonObject.getInteger("is_need_knowledge_base");

                    //获取flow_info对象
                    JSONObject flow_info = jsonObject.getJSONObject("flowInfo");

                    //创建第五个节点信息
                    // 创建外层JSON对象
                    JSONObject mainObj = new JSONObject();
                    mainObj.put("type", "commit");
                    mainObj.put("flow_no", _flow_no2);
                    mainObj.put("flow_type", "vpl");
                    mainObj.put("flow_level", 5);
                    mainObj.put("knowledge_base_key", _knowledge_base_key2);
                    mainObj.put("is_need_knowledge_base", _is_need_knowledge_base2);

                    // 创建嵌套的flowInfo对象
                    JSONObject flowInfo = new JSONObject();
                    flowInfo.put("comments", flow_info.getString("comments"));  // 显式声明null值
                    flowInfo.put("flow_approver", flow_info.getString("flow_approver"));
                    mainObj.put("flowInfo", flowInfo);

                    // 转换为字符串
                    String jsonString = mainObj.toString();
                    return operateTaskFlow(jsonString);
                } else {
                    return first4;
                }

            } else {
                return ResultUtil.error(500, "参数为空", "", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }
    }

    private static List<String> convertKeyListToStringList(JSONArray keyList, String keyName) {
        // 如果 keyList 为空或 null，返回空列表
        if (keyList == null || keyList.isEmpty()) {
            return new ArrayList<>();
        }

        // 创建 List 用于存储 knowledge_base_key 的值
        List<String> result = new ArrayList<>();

        // 遍历 JSONArray
        for (Object obj : keyList) {
            // 确保元素是 JSONObject
            if (obj instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) obj;
                // 提取 knowledge_base_key 的值
                String key = jsonObject.getString(keyName);
                // 如果 key 不为 null，添加到结果列表
                if (key != null) {
                    result.add(key);
                }
            }
            // 空对象或其他类型直接跳过
        }

        return result;
    }

    @Override
    public Result uploadKnowledgeBaseData(MultipartFile zipFile, String type) {
        try {
            if (type == null || type.isEmpty()) {
                return ResultUtil.error(500, "type不可以为空", "", null);
            }

            //已经获取到所有的文件信息
            Map<String, File> map = processZip(zipFile);
            //获取excel文件
            File excelFile = map.get("excel");
            if (excelFile == null) {
                return ResultUtil.error(500, "请上传excel文件", "", null);
            }
            //获取图片文件
            List<File> imageFiles = new ArrayList<>(map.values());
            imageFiles.remove(excelFile);

            List<Map<String, String>> processedList = new ArrayList<>();
            List<Map<String, String>> excelData = new ArrayList<>();
            String tempTemplateName = null;
            //器件流程
            //解析excel
            if (type.equalsIgnoreCase("device")) {
                tempTemplateName = "deviceType";

                processedList = ExcelUtils.parseExcel3(excelFile, 0, 0, 0);

                if (processedList != null && processedList.size() > 0) {
                    String columnName1 = "器件专用";
                    String columnName2 = "器件编码";
                    String columnName3 = "器件封装";
                    String columnName4 = "装联方式";
                    String columnName5 = "器件大类";
                    String columnName6 = "器件小类";
                    String columnName7 = "设计阶段";
                    String columnName8 = "级别";
                    String columnName9 = "工艺知识checklist";
                    String columnName10 = "检查方法";
                    String columnName11 = "规则来源";
                    String columnName12 = "图片";
                    String columnName13 = "附件";

                    for (Map<String, String> row : processedList) {
                        Map<String, String> tempMap = new HashMap<>();

                        String column1_value = row.get(columnName1);
                        String column2_value = row.get(columnName2);
                        String column3_value = row.get(columnName3);
                        String column4_value = row.get(columnName4);
                        String column5_value = row.get(columnName5);
                        String column6_value = row.get(columnName6);
                        String column7_value = row.get(columnName7);
                        String column8_value = row.get(columnName8);
                        String column9_value = row.get(columnName9);
                        String column10_value = row.get(columnName10);
                        String column11_value = row.get(columnName11);
                        String column12_value = row.get(columnName12);
                        String column13_value = row.get(columnName13);

                        tempMap.put(columnName1, column1_value);
                        tempMap.put(columnName2, column2_value);
                        tempMap.put(columnName3, column3_value);
                        tempMap.put(columnName4, column4_value);
                        tempMap.put(columnName5, column5_value);
                        tempMap.put(columnName6, column6_value);
                        tempMap.put(columnName7, column7_value);
                        tempMap.put(columnName8, column8_value);
                        tempMap.put(columnName9, column9_value);
                        tempMap.put(columnName10, column10_value);
                        tempMap.put(columnName11, column11_value);
                        tempMap.put(columnName12, column12_value);
                        tempMap.put(columnName13, column13_value);
                        excelData.add(tempMap);
                    }
                    //return ResultUtil.success(processedList);
                } else {
                    return ResultUtil.error(500, "模板中没有有效数据,请检查", "", null);
                }
            } else if (type.equalsIgnoreCase("design")) {
                tempTemplateName = "designType";

                processedList = ExcelUtils.parseExcel3(excelFile, 0, 0, 0);

                if (processedList != null && processedList.size() > 0) {
                    String columnName1 = "产品线";
                    String columnName2 = "单板类型";
                    String columnName3 = "工艺大类";
                    String columnName4 = "工艺小类";
                    String columnName5 = "工艺子类";
                    String columnName6 = "设计阶段";
                    String columnName7 = "级别";
                    String columnName8 = "工艺知识checklist";
                    String columnName9 = "检查方法";
                    String columnName10 = "规则来源";
                    String columnName11 = "图片";
                    String columnName12 = "附件";

                    for (Map<String, String> row : processedList) {
                        Map<String, String> tempMap = new HashMap<>();

                        String column1_value = row.get(columnName1);
                        String column2_value = row.get(columnName2);
                        String column3_value = row.get(columnName3);
                        String column4_value = row.get(columnName4);
                        String column5_value = row.get(columnName5);
                        String column6_value = row.get(columnName6);
                        String column7_value = row.get(columnName7);
                        String column8_value = row.get(columnName8);
                        String column9_value = row.get(columnName9);
                        String column10_value = row.get(columnName10);
                        String column11_value = row.get(columnName11);
                        String column12_value = row.get(columnName12);

                        tempMap.put(columnName1, column1_value);
                        tempMap.put(columnName2, column2_value);
                        tempMap.put(columnName3, column3_value);
                        tempMap.put(columnName4, column4_value);
                        tempMap.put(columnName5, column5_value);
                        tempMap.put(columnName6, column6_value);
                        tempMap.put(columnName7, column7_value);
                        tempMap.put(columnName8, column8_value);
                        tempMap.put(columnName9, column9_value);
                        tempMap.put(columnName10, column10_value);
                        tempMap.put(columnName11, column11_value);
                        tempMap.put(columnName12, column12_value);
                        excelData.add(tempMap);
                    }
                    //return ResultUtil.success(processedList);
                } else {
                    return ResultUtil.error(500, "模板中没有有效数据,请检查", "", null);
                }
            } else {
                return ResultUtil.error(500, "type不正确", "", null);
            }

            String _tempCreater = UserHeaderHolder.getUserId();
            if (excelData != null && excelData.size() > 0) {
                for (int i = 0; i < excelData.size(); i++) {
                    Map<String, String> tempMap = excelData.get(i);

                    //region 创建流程信息
                    String _flow_no = "";
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                    String currentDate = sdf.format(new Date());
                    TbFlowProcessMain byFlowNo = tbFlowProcessMainDao.getByFlowNo(currentDate);
                    int currentSeq = 0;
                    if (byFlowNo != null) {
                        currentSeq = byFlowNo.getSeq();
                    }
                    currentSeq++;
                    //流程编号
                    _flow_no = currentDate + String.format("%05d", currentSeq);
                    String version = UUID.randomUUID().toString();
                    //获取审核流程
                    List<TbFlowDetail> listFlow = tbFlowDetailDao.getFolwListByType(type);
                    //写入审核流程信息
                    List<TbFlowProcessDetail> listFlowTemplate = new ArrayList<>();
                    for (TbFlowDetail flow : listFlow) {
                        listFlowTemplate.add(new TbFlowProcessDetail(
                                _flow_no,
                                flow.flow_type,
                                flow.flow_name,
                                flow.flow_level,
                                _tempCreater,
                                2,
                                flow.sort,
                                _tempCreater,
                                new Date()));
                    }

                    TbFlowProcessMain tbFlowProcessMain = new TbFlowProcessMain();
                    tbFlowProcessMain.setFlow_no(_flow_no);
                    tbFlowProcessMain.setFlow_type(type);
                    tbFlowProcessMain.setSeq(currentSeq);
                    //tbFlowProcessMain.setNow_level(firstFlowProcessDetail.getFlow_level());
                    //tbFlowProcessMain.setNow_approver(firstFlowProcessDetail.getFlow_approver());
                    tbFlowProcessMain.setStatus(3);
                    tbFlowProcessMain.setCreate_time(new Date());
                    tbFlowProcessMain.setKnowledge_base_key(version);
                    tbFlowProcessMain.setCreate_user(_tempCreater);

                    Integer _sort = 1;
                    List<TbTaskVersion> listTaskVersion = tbTaskVersionDao.getNewestTaskVersion(type);
                    if (listTaskVersion != null && listTaskVersion.size() > 0) {
                        TbTaskVersion tbTaskVersion = listTaskVersion.get(0);
                        _sort = tbTaskVersion.getSort() + 1;
                    }
                    TbTaskVersion tbTaskVersion = new TbTaskVersion();
                    tbTaskVersion.setVersion(version);
                    tbTaskVersion.setTask_type(type);
                    tbTaskVersion.setCreate_user(_tempCreater);
                    tbTaskVersion.setCreate_time(new Date());
                    tbTaskVersion.setSort(_sort);
                    tbTaskVersion.setFlow_no(_flow_no);
                    tbTaskVersion.setStatus(3);

                    List<TbTaskTemplateData> resultList = new ArrayList<>();
                    //处理版本明细表数据
                    if (!tempTemplateName.isEmpty()) {
                        List<TbTemplateVersion> listVersion = tbTemplateVersionDao.getNewestTemplateVersion2(tempTemplateName);

                        if (listVersion != null && listVersion.size() > 0) {
                            TbTemplateVersion tbTemplateVersion = listVersion.get(0);

                            List<TbTemplate> listTemplate = tbTemplateDao.getTbTemplateByVersion(tempTemplateName, tbTemplateVersion.getVersion());
                            if (listTemplate != null && listTemplate.size() > 0) {
                                //先转成TbTaskTemplateData
                                String final_flow_no = _flow_no;

                                List<TbTaskTemplateData> listTaskTemplateData = listTemplate.stream()
                                        .map(template -> {
                                            TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                                            taskTemplateData.setFlow_no(final_flow_no);
                                            taskTemplateData.setFlow_level(1);
                                            taskTemplateData.setVersion(template.getVersion());
                                            taskTemplateData.setTemplate_type(template.getTemplate_type());
                                            taskTemplateData.setParent_id(template.getParent_id());
                                            taskTemplateData.setParam_name(template.getParam_name());
                                            taskTemplateData.setParam_name_en(template.getParam_name_en());
                                            taskTemplateData.setParam_key(template.getParam_key());
                                            taskTemplateData.setParent_param_key(template.getParent_param_key());
                                            taskTemplateData.setParam_type(template.getParam_type());
                                            taskTemplateData.setLevel(template.getLevel());
                                            taskTemplateData.setSelect_level(template.getSelect_level());
                                            taskTemplateData.setParent_select_id(template.getParent_select_id());
                                            taskTemplateData.setTip(template.getTip());
                                            taskTemplateData.setRemark(template.getRemark());
                                            taskTemplateData.setSort(template.getSort());
                                            taskTemplateData.setIs_value(template.getIs_value());
                                            return taskTemplateData;
                                        })
                                        //.filter(taskTemplateData -> taskTemplateData.getIs_value() == 2)
                                        .collect(Collectors.toList());

                                //这个拿到的只是模板数据,那么要先添加所有的数据,row为-1,然后再循环excel的数据,加一行行号为0的就可以了
                                if (listTaskTemplateData != null && listTaskTemplateData.size() > 0) {
                                    //先添加一个row为-1的
                                    List<TbTaskTemplateData> minusOneList = listTaskTemplateData.stream()
                                            .map(template -> {
                                                TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                                                taskTemplateData.setFlow_no(template.getFlow_no());
                                                taskTemplateData.setFlow_level(template.getFlow_level());
                                                taskTemplateData.setVersion(template.getVersion());
                                                taskTemplateData.setTemplate_type(template.getTemplate_type());
                                                taskTemplateData.setParent_id(template.getParent_id());
                                                taskTemplateData.setParam_name(template.getParam_name());
                                                taskTemplateData.setParam_name_en(template.getParam_name_en());
                                                taskTemplateData.setParam_key(template.getParam_key());
                                                taskTemplateData.setParent_param_key(template.getParent_param_key());
                                                taskTemplateData.setParam_type(template.getParam_type());
                                                taskTemplateData.setLevel(template.getLevel());
                                                taskTemplateData.setSelect_level(template.getSelect_level());
                                                taskTemplateData.setParent_select_id(template.getParent_select_id());
                                                taskTemplateData.setTip(template.getTip());
                                                taskTemplateData.setRemark(template.getRemark());
                                                taskTemplateData.setSort(template.getSort());
                                                taskTemplateData.setIs_value(template.getIs_value());
                                                taskTemplateData.setRow_sort(-1);
                                                return taskTemplateData;
                                            })
                                            .collect(Collectors.toList());
                                    //这个是为0的
                                    List<TbTaskTemplateData> zeroList = listTaskTemplateData.stream()
                                            .map(template -> {
                                                TbTaskTemplateData taskTemplateData = new TbTaskTemplateData();
                                                taskTemplateData.setFlow_no(template.getFlow_no());
                                                taskTemplateData.setFlow_level(template.getFlow_level());
                                                taskTemplateData.setVersion(template.getVersion());
                                                taskTemplateData.setTemplate_type(template.getTemplate_type());
                                                taskTemplateData.setParent_id(template.getParent_id());
                                                taskTemplateData.setParam_name(template.getParam_name());
                                                taskTemplateData.setParam_name_en(template.getParam_name_en());
                                                taskTemplateData.setParam_key(template.getParam_key());
                                                taskTemplateData.setParent_param_key(template.getParent_param_key());
                                                taskTemplateData.setParam_type(template.getParam_type());
                                                taskTemplateData.setLevel(template.getLevel());
                                                taskTemplateData.setSelect_level(template.getSelect_level());
                                                taskTemplateData.setParent_select_id(template.getParent_select_id());
                                                taskTemplateData.setTip(template.getTip());
                                                taskTemplateData.setRemark(template.getRemark());
                                                taskTemplateData.setSort(template.getSort());
                                                taskTemplateData.setIs_value(template.getIs_value());
                                                taskTemplateData.setRow_sort(0);
                                                return taskTemplateData;
                                            })
                                            .filter(taskTemplateData -> taskTemplateData.getIs_value() == 2)
                                            .collect(Collectors.toList());

                                    for (TbTaskTemplateData zero : zeroList) {
                                        //等于1的是下拉框的值
                                        if (zero.getIs_value() != null && zero.getIs_value() == 2) {
                                            String ParamName = tempMap.get(zero.getParam_name());
                                            if (ParamName != null) {
                                                //那就是找到了值的,相当于在模板中有对应字段,那么就要去看是什么类型的了
                                                //需要单独处理的就是单选下拉框,多选下拉框,图片
                                                //单选
                                                if (zero.getParam_type() != null && zero.getParam_type() == 2) {

                                                    String matchKey = "";
                                                    if (zero.getParent_select_id() != null && !zero.getParent_select_id().equalsIgnoreCase("0")) {
                                                        matchKey = zero.getParent_select_id();
                                                    }


                                                    if (matchKey != null && !matchKey.isEmpty()) {
                                                        String finalMatchKey = matchKey;
                                                        String valueKey = zeroList.stream()
                                                                .filter(item -> item.getParam_key().equalsIgnoreCase(finalMatchKey))
                                                                .map(TbTaskTemplateData::getParam_value)
                                                                .filter(Objects::nonNull) // 过滤 null 值
                                                                .collect(Collectors.joining(",")); // 无匹配时返回 ""，无需 orElse

                                                        //那就要去找对应的值的key
                                                        String result = listTaskTemplateData.stream()
                                                                .filter(item -> ParamName.equals(item.getParam_name()) && valueKey.equalsIgnoreCase(item.getParent_select_id()))
                                                                .map(TbTaskTemplateData::getParam_key)
                                                                .filter(Objects::nonNull) // 过滤 null 值
                                                                .collect(Collectors.joining(",")); // 无匹配时返回 ""，无需 orElse

                                                        zero.setParam_value(result);
                                                    } else {
                                                        //那就要去找对应的值的key
                                                        String result = listTaskTemplateData.stream()
                                                                .filter(item -> ParamName.equals(item.getParam_name()))
                                                                .map(TbTaskTemplateData::getParam_key)
                                                                .filter(Objects::nonNull) // 过滤 null 值
                                                                .collect(Collectors.joining(",")); // 无匹配时返回 ""，无需 orElse

                                                        zero.setParam_value(result);
                                                    }
                                                }
                                                //附件
                                                else if (zero.getParam_type() != null && zero.getParam_type() == 3) {
                                                    zero.setParam_value(handleExcelFile(imageFiles, _flow_no, zero.getParam_type(), ParamName));
                                                }
                                                //图片
                                                else if (zero.getParam_type() != null && zero.getParam_type() == 4) {
                                                    zero.setParam_value(handleExcelFile(imageFiles, _flow_no, zero.getParam_type(), ParamName));
                                                }
                                                //多选
                                                else if (zero.getParam_type() != null && zero.getParam_type() == 5) {
                                                    //那就要去找对应的值的key
                                                    List<String> targetParamNames = Arrays.stream(ParamName.split("/"))  // 1. 按斜杠分割
                                                            .map(part ->
                                                                    part.replaceAll(           // 2. 清理每个分段
                                                                            "[^\\w\\s\\u4e00-\\u9fa5]", ""  // 正则：保留字母、数字、下划线、空格、汉字[1,5](@ref)
                                                                    ).replaceAll("\\s+", "")  // 3. 额外移除空格[6,7](@ref)
                                                            )
                                                            .filter(cleaned -> !cleaned.isEmpty()) // 4. 过滤空字符串
                                                            .collect(Collectors.toList());

                                                    String result = listTaskTemplateData.stream()
                                                            .filter(item -> targetParamNames.contains(item.getParam_name()) // 匹配列表中的任意 param_name
                                                            )
                                                            .map(TbTaskTemplateData::getParam_key)
                                                            .filter(Objects::nonNull) // 过滤 null 值
                                                            .collect(Collectors.joining(",")); // 无匹配时返回 ""

                                                    String[] resultArray = Arrays.stream(result.split(","))
                                                            .map(String::trim)      // 移除每个元素前后空格
                                                            .filter(s -> !s.isEmpty()) // 过滤空字符串
                                                            .toArray(String[]::new);  // 转为数组

                                                    String jsonArray = new ObjectMapper().writeValueAsString(resultArray);

                                                    zero.setParam_value(jsonArray);
                                                } else {
                                                    zero.setParam_value(ParamName);
                                                }
                                            }
                                        }
                                    }
                                    resultList.addAll(minusOneList);
                                    resultList.addAll(zeroList);

                                } else {
                                    return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                                }
                            } else {
                                return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                            }

                        } else {
                            return ResultUtil.error(500, "未查询到已分发的模板", "", null);
                        }
                    } else {
                        return ResultUtil.error(500, "flow_type 参数不正确", "", null);
                    }
                    //写入明细数据表
                    tbTaskTemplateDataDao.insertTaskTemplateDataBatch(resultList);
                    //流程主表
                    tbFlowProcessMainDao.insertFlowProcessMain(tbFlowProcessMain);
                    //流程明细表
                    tbFlowProcessDetailDao.insertFlowTemplateBatch(listFlowTemplate);
                    //版本主表
                    tbTaskVersionDao.insertTaskVersion(tbTaskVersion);

                    //归档数据库写表信息
                    List<TbTaskTemplateData> tbTaskTemplateDataList = tbTaskTemplateDataDao.getTaskTemplateDataByFlowNo(_flow_no);
                    if (tbTaskTemplateDataList != null && tbTaskTemplateDataList.size() > 0) {
                        List<TbKnowledgeBaseData> tbKnowledgeBaseDataList = new ArrayList<>();

                        // 遍历 TbTaskTemplateData 列表，并将每个元素转换为 TbKnowledgeBaseData
                        for (TbTaskTemplateData tbTaskTemplateData : tbTaskTemplateDataList) {
                            TbKnowledgeBaseData tbKnowledgeBaseData = new TbKnowledgeBaseData();
                            // 将 TbTaskTemplateData 的字段值复制到 TbKnowledgeBaseData
                            tbKnowledgeBaseData.setId(tbTaskTemplateData.getId());
                            tbKnowledgeBaseData.setFlow_no(tbTaskTemplateData.getFlow_no());
                            tbKnowledgeBaseData.setFlow_level(tbTaskTemplateData.getFlow_level());
                            tbKnowledgeBaseData.setVersion(tbTaskTemplateData.getVersion());
                            tbKnowledgeBaseData.setTemplate_type(tbTaskTemplateData.getTemplate_type());
                            tbKnowledgeBaseData.setParent_id(tbTaskTemplateData.getParent_id());
                            tbKnowledgeBaseData.setParam_name(tbTaskTemplateData.getParam_name());
                            tbKnowledgeBaseData.setParam_name_en(tbTaskTemplateData.getParam_name_en());
                            tbKnowledgeBaseData.setParam_key(tbTaskTemplateData.getParam_key());
                            tbKnowledgeBaseData.setParam_type(tbTaskTemplateData.getParam_type());
                            tbKnowledgeBaseData.setParam_value(tbTaskTemplateData.getParam_value());
                            tbKnowledgeBaseData.setLevel(tbTaskTemplateData.getLevel());
                            tbKnowledgeBaseData.setSelect_level(tbTaskTemplateData.getSelect_level());
                            tbKnowledgeBaseData.setParent_select_id(tbTaskTemplateData.getParent_select_id());
                            tbKnowledgeBaseData.setTip(tbTaskTemplateData.getTip());
                            tbKnowledgeBaseData.setRemark(tbTaskTemplateData.getRemark());
                            tbKnowledgeBaseData.setCreate_user(tbTaskTemplateData.getCreate_user());
                            tbKnowledgeBaseData.setCreate_time(tbTaskTemplateData.getCreate_time());
                            tbKnowledgeBaseData.setUpdate_user(tbTaskTemplateData.getUpdate_user());
                            tbKnowledgeBaseData.setUpdate_time(tbTaskTemplateData.getUpdate_time());
                            tbKnowledgeBaseData.setStatus(tbTaskTemplateData.getStatus());
                            tbKnowledgeBaseData.setChildren(tbTaskTemplateData.getChildren());
                            tbKnowledgeBaseData.setParent_param_key(tbTaskTemplateData.getParent_param_key());
                            tbKnowledgeBaseData.setSort(tbTaskTemplateData.getSort());
                            tbKnowledgeBaseData.setRow_sort(tbTaskTemplateData.getRow_sort());
                            tbKnowledgeBaseData.setRow_sort_old(tbTaskTemplateData.getRow_sort_old());
                            tbKnowledgeBaseData.setIs_Add(tbTaskTemplateData.getIs_Add());
                            tbKnowledgeBaseData.setIs_value(tbTaskTemplateData.getIs_value());
                            tbKnowledgeBaseData.setChildrenCount(tbTaskTemplateData.getChildrenCount());
                            tbKnowledgeBaseData.setKnowledge_base_key(tbFlowProcessMain.getKnowledge_base_key());

                            // 将转换后的 TbKnowledgeBaseData 添加到新的列表中
                            tbKnowledgeBaseDataList.add(tbKnowledgeBaseData);
                        }

                        TbKnowledgeBaseData tbKnowledgeBaseData = new TbKnowledgeBaseData();
                        tbKnowledgeBaseData.setKnowledge_base_key(tbFlowProcessMain.getKnowledge_base_key());
                        //删除知识库的数据信息
                        tbKnowledgeBaseDataDao.deleteTaskTemplateData(tbKnowledgeBaseData);
                        tbKnowledgeBaseDataDao.insertTbKnowledgeBaseDataBatch(tbKnowledgeBaseDataList);
                    }
                    //endregion
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), "", null);
        }

        return ResultUtil.success("导入成功");
    }

    public static Map<String, File> processZip(MultipartFile zipFile) throws IOException {
        if (zipFile.isEmpty()) {
            throw new IOException("ZIP文件为空");
        }

        byte[] zipData = zipFile.getBytes();

        // 检查文件头
        if (zipData.length < 4 ||
                !(zipData[0] == 0x50 && zipData[1] == 0x4B && (zipData[2] == 0x03 || zipData[2] == 0x05 || zipData[2] == 0x07) && (zipData[3] == 0x04 || zipData[3] == 0x06 || zipData[3] == 0x08))) {
            throw new IOException("不是有效的ZIP文件格式");
        }

        Path tempDir = Files.createTempDirectory("zip-extract");
        Map<String, File> files = new HashMap<>();
        boolean success = false;

        String[] tryCharsets = {
                "UTF-8", "GBK", "GB18030", "BIG5", "ISO-8859-1", "CP437", "Cp850", Charset.defaultCharset().name()
        };

        for (String charsetName : tryCharsets) {
            try (InputStream bais = new ByteArrayInputStream(zipData);
                 ZipArchiveInputStream zis = new ZipArchiveInputStream(bais, charsetName, true, true)) {

                ArchiveEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    if (entry.isDirectory() || entry.getName() == null) continue;

                    String fileName = new File(entry.getName()).getName();
                    if (fileName.isEmpty()) continue;

                    Path filePath = tempDir.resolve(fileName);
                    Files.createDirectories(filePath.getParent());
                    Files.copy(zis, filePath, StandardCopyOption.REPLACE_EXISTING);

                    if (fileName.endsWith(".xlsx")) {
                        files.put("excel", filePath.toFile());
                    } else {
                        files.put(fileName, filePath.toFile());
                    }
                    success = true;
                }

                if (success) {
                    System.out.println("成功使用编码: " + charsetName);
                    break;
                }
            } catch (Exception e) {
                System.err.println("编码尝试失败 [" + charsetName + "]: " + e.getMessage());
            }
        }

        if (!success) {
            throw new IOException("无法解压ZIP文件，所有编码尝试均失败。尝试的编码包括: " + String.join(", ", tryCharsets));
        }

        return files;
    }

    public static Map<String, File> processZip2(MultipartFile zipFile) throws IOException {
        Path tempDir = Files.createTempDirectory("zip-extract");
        Map<String, File> files = new HashMap<>();

        // 调整编码尝试顺序，并补充一些中文环境下常用的编码
        String[] tryCharsets = {
                "UTF-8",       // 优先尝试UTF-8，越来越多的工具默认使用UTF-8
                "GBK",         // 中文Windows常用
                "GB18030",     // GBK的扩展，支持更多字符（如人名、古汉语生僻字）
                "BIG5",        // 繁体中文（香港、台湾地区可能用到）
                "ISO-8859-1",  // 西欧编码，有时可能被误用
                Charset.defaultCharset().name() // 系统默认编码
        };

        // 先将MultipartFile内容读入字节数组，确保流可重复读取
        byte[] zipData = zipFile.getBytes();
        boolean success = false; // 标记是否成功解压出至少一个文件

        for (String charsetName : tryCharsets) {
            try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipData), Charset.forName(charsetName))) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        zis.closeEntry();
                        continue;
                    }

                    // 处理文件名：仅保留文件名，忽略路径
                    String fileName = new File(entry.getName()).getName();
                    Path filePath = tempDir.resolve(fileName);

                    Files.createDirectories(filePath.getParent()); // 确保父目录存在
                    Files.copy(zis, filePath, StandardCopyOption.REPLACE_EXISTING);
                    zis.closeEntry(); // 释放当前Entry资源

                    // 分类存储文件
                    if (fileName.endsWith(".xlsx")) {
                        files.put("excel", filePath.toFile());
                    } else {
                        files.put(fileName, filePath.toFile());
                    }

                    success = true; // 标记此编码成功解压出文件
                }

                // 如果当前编码成功解压出文件（不局限于excel），就跳出循环
                if (success) {
                    System.out.println("成功使用编码: " + charsetName);
                    break;
                }
            } catch (Exception e) {
                // 当前编码尝试失败，记录日志并继续尝试下一个编码
                System.err.println("尝试编码 " + charsetName + " 时失败: " + e.getMessage());
                // 继续尝试下一个编码
            }
        }

        if (!success) {
            // 所有编码都尝试失败
            throw new IOException("无法解压ZIP文件，所有编码尝试均失败。尝试的编码包括: " + String.join(", ", tryCharsets));
        }

        return files;
    }

    public static Map<String, File> processZip3(MultipartFile zipFile) throws IOException {
        Path tempDir = Files.createTempDirectory("zip-extract");
        Map<String, File> files = new HashMap<>();

        String[] tryCharsets = {"GBK", "UTF-8", "ISO-8859-1", Charset.defaultCharset().name()};

        for (String charsetName : tryCharsets) {
            try (ZipInputStream zis = new ZipInputStream(zipFile.getInputStream(), Charset.forName(charsetName))) {
                ZipEntry entry;
                while ((entry = zis.getNextEntry()) != null) {
                    if (entry.isDirectory()) continue;
                    // 处理子目录：仅保留文件名，忽略路径
                    String fileName = new File(entry.getName()).getName();
                    Path filePath = tempDir.resolve(fileName); // 直接存储到临时目录根下

                    // 确保父目录存在
                    Files.createDirectories(filePath.getParent());

                    // 复制文件并显式关闭当前Entry
                    Files.copy(zis, filePath, StandardCopyOption.REPLACE_EXISTING);
                    zis.closeEntry(); // 关键！释放当前Entry资源

                    // 分类存储文件
                    if (fileName.endsWith(".xlsx")) {
                        files.put("excel", filePath.toFile());
                    } else {
                        files.put(fileName, filePath.toFile()); // 使用无路径的文件名作为Key
                    }
                    //else if (fileName.matches(".*\\.(jpg|png|jpeg)$")) {
                    //    files.put(fileName, filePath.toFile()); // 使用无路径的文件名作为Key
                    //}
                }
            }

            File excelFile = files.get("excel");
            if (excelFile != null) {
                break;
            }
        }


        return files;
    }


    public String handleExcelFile(List<File> excelFiles, String _flow_no, Integer _param_type, String fileName) {
        String keyStr = "";
        try {
            if (fileName != null && !fileName.isEmpty()) {
                List<String> keyList = new ArrayList<>();

                List<String> targetParamNames = Arrays.stream(fileName.split("/"))  // 1. 按斜杠分割
                        //.map(part ->
                        //        part.replaceAll(           // 2. 清理每个分段
                        //                "[^\\w\\s\\u4e00-\\u9fa5]", ""  // 正则：保留字母、数字、下划线、空格、汉字[1,5](@ref)
                        //        ).replaceAll("\\s+", "")  // 3. 额外移除空格[6,7](@ref)
                        //)
                        .filter(cleaned -> !cleaned.isEmpty()) // 4. 过滤空字符串
                        .collect(Collectors.toList());

                if (targetParamNames != null && targetParamNames.size() > 0) {
                    for (String tempName : targetParamNames) {
                        //excelFiles里面去找有没有相同名字的图片
                        for (File file : excelFiles) {
                            if (file.getName().startsWith(tempName)) {
                                //那就是找到了这个图片
                                String oldName = file.getName();
                                String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());

                                Map<String, String> map = new HashMap<>();

                                if (_param_type == 4) {
                                    if (env.equals("dev")) {
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String format = sdf.format(new Date());
                                        File folder = new File(fileSaveUrl + "knowledgeBase" + File.separator + format);
                                        if (!folder.exists()) folder.mkdirs();

                                        File destFile = new File(folder, newName);
                                        Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); // 安全复制文件
                                        String filePath = "knowledgeBase" + File.separator + format + File.separator + newName;

                                        map.put("name", newName);
                                        map.put("oldName", oldName);
                                        map.put("relatePath", filePath);
                                        String base64 = s3UploadFileService.getImageBase64FromUrl(filePath);
                                        map.put("imageBase64", CommonUtils.base64Prefix() + base64);
                                    } else {
                                        String address = s3UploadFileService.uploadFile2("knowledgeBase", file);
                                        if (address != null) {
                                            map.put("oldName", oldName);
                                            map.put("name", newName);
                                            map.put("relatePath", address);
                                            map.put("url", url + "/" + fileBucket + "/" + address);
                                            String base64 = "";
                                            base64 = s3UploadFileService.getImageBase64FromUrl(url + "/" + fileBucket + "/" + address);
                                            map.put("imageBase64", CommonUtils.base64Prefix() + base64);
                                        }
                                    }

                                } else if (_param_type == 3) {
                                    if (env.equals("dev")) {
                                        //获取项目目录
                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String format = sdf.format(new Date());
                                        File folder = new File(fileSaveUrl + "knowledgeBase\\" + format);

                                        String filePath = "";
                                        if (!folder.isDirectory()) {
                                            folder.mkdirs();
                                        }

                                        File destFile = new File(folder, newName);
                                        Files.copy(file.toPath(), destFile.toPath(), StandardCopyOption.REPLACE_EXISTING); // 安全复制文件

                                        filePath = "knowledgeBase\\" + format + "\\" + newName;
                                        map.put("name", newName);
                                        map.put("oldName", oldName);
                                        map.put("relatePath", filePath);
                                    } else {

                                        String secretKey = String.valueOf(UUID.randomUUID()).substring(0, 30);
                                        SfsUtils.SfsFileData data = sfsUtils.upload2(file, secretKey);
                                        if (data != null) {
                                            String fileSid = data.getFileSid();
                                            if (!StringUtils.isBlank(fileSid)) {
                                                map.put("oldName", oldName);
                                                map.put("secretKey", secretKey);
                                                map.put("fileSid", fileSid);
                                            }
                                        }
                                    }
                                }

                                if (map != null) {
                                    String _param_key = String.valueOf(UUID.randomUUID());
                                    keyList.add(_param_key);
                                    TbKnowledgeBaseFile tbKnowledgeBaseFile = new TbKnowledgeBaseFile();
                                    tbKnowledgeBaseFile.setFlow_no(_flow_no);
                                    tbKnowledgeBaseFile.setFlow_level(1);
                                    tbKnowledgeBaseFile.setParam_key(_param_key);

                                    String filename = map.get("oldName");
                                    tbKnowledgeBaseFile.setFile_name(filename);
                                    tbKnowledgeBaseFile.setFile_extend(filename.substring(filename.lastIndexOf(".") + 1));
                                    tbKnowledgeBaseFile.setFile_relate_path(map.get("relatePath"));
                                    tbKnowledgeBaseFile.setFile_type(_param_type);
                                    //valueObject.get("url") == null ? null : valueObject.get("url").toString()
                                    tbKnowledgeBaseFile.setUrl(map.get("relatePath"));
                                    tbKnowledgeBaseFile.setSecret_key(map.get("secretKey"));
                                    tbKnowledgeBaseFile.setFile_sid(map.get("fileSid"));

                                    List<TbKnowledgeBaseFile> tbKnowledgeBaseFileList = new ArrayList<>();
                                    tbKnowledgeBaseFileList.add(tbKnowledgeBaseFile);

                                    tbKnowledgeBaseFileDao.insertTbKnowledgeBaseFileBatch(tbKnowledgeBaseFileList);
                                }
                            }
                        }
                    }
                }

                if (keyList != null && keyList.size() > 0) {
                    //用逗号拼接起来变成字符串
                    keyStr = String.join(",", keyList);
                }
            } else {
                keyStr = "";
            }
        } catch (Exception e) {
            keyStr = "";
        }
        return keyStr;
    }

}
